【问题标题】:What's the best way to edit a text file record using shell?使用 shell 编辑文本文件记录的最佳方法是什么?
【发布时间】:2009-12-10 02:24:36
【问题描述】:

我有这样存储记录的数据文件:

make=honda|model=civic|color=red
make=toyota|model=corolla|color=blue

检测(基于 make 字段)文件中是否存在给定 make 然后用新记录替换它的最佳方法是什么? (使用 shell 脚本)

【问题讨论】:

  • 你已经展示了你的数据文件,现在展示你想要修改的实际文件并通过示例描述你的最终输出

标签: shell unix


【解决方案1】:

出于您的目的,最好的解决方案可能是the stream editorawk

【讨论】:

  • 我已经知道如何检测记录 (awk)。但是有什么好的方法可以代替吗?我可以以某种方式使用 SED 来做到这一点吗?
  • 如果有某种方法可以将“流编辑器”这个词变成某种神奇的门户到文档本身...
【解决方案2】:

这是一个使用sed 命令的脚本:

filename='cars'
make='toyota'
replacement='make=nissan|model=sentra|color=green'
sed "s/^make=$make.*/$replacement/" $filename

icarus127 的回答存在几个问题,我已在此处修复并解决了这些问题:

filename='cars'
saveIFS="$IFS"
IFS=$'\n'
# no need to call external cat, make the array at the same time the file is read
lines=($(<$filename))
# IMO, it's better and makes a difference to save and restore IFS instead of unsetting it
IFS="$saveIFS"

make='toyota'
replacement='make=nissan|model=sentra|color=green'

# the array variable MUST be quoted here or it won't work correctly
for line in "${lines[@]}"
do
    # you can use Bash's regex matching to avoid repeatedly calling
    # multiple external programs in a loop
    if [[ $line =~ ^make=$make ]]
    then
        echo "$replacement"
    else
        echo "$line"
    fi    
done

然而,那个(和cat 版本)将整个文件读入一个数组,如果它很大,这可能是个问题。最好在带有重定向的while 循环中使用read

filename='cars'

make='toyota'
replacement='make=nissan|model=sentra|color=green'

while read -r line
do
    # you can use Bash's regex matching to avoid repeatedly calling
    # multiple external programs in a loop
    if [[ $line =~ ^make=$make ]]
    then
        echo "$replacement"
    else
        echo "$line"
    fi    
done < "$filename"

【讨论】:

  • +1 用于改进我的脚本。我充其量只是一个新手,很高兴看到更好的做事方式。谢谢:)
【解决方案3】:

这应该在 bash 中完成。

#get the file and create an array separated by new lines
lines=$(cat $filename)
IFS=$'\n'
lines=( $lines )
unset IFS


for line in ${lines[@]}
do
    #Get the value of make from the current line
    make=$(echo "$line" | cut -d "|" -f1 | cut -d "=" -f2)

    if [[ "$make" == "$makeImLookingFor" ]]
    then
        echo "modified line"
    else
        echo "$line"
    fi
done

【讨论】:

    【解决方案4】:

    sed 这是一种方法

    temp.txt 的内容 制造=本田|车型=思域|颜色=红色 make=toyota|model=corolla|color=blue

    new_rec="make=honda|model=civic|color=blue"

    $ sed -e "s/^make=honda.*/$new_rec/g" temp.txt 品牌=本田|车型=思域|颜色=蓝色 make=toyota|model=corolla|color=blue

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      相关资源
      最近更新 更多