使用shell编辑文本文件记录的最佳方法是什么?

时间:2009-12-10 02:24:37

标签: shell unix

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

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

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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版本)将整个文件读入一个数组,如果它很大,这可能是一个问题。最好在read循环中使用while并重定向:

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"

答案 2 :(得分:0)

这应该在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

答案 3 :(得分:0)

by sed这是一种方式

temp.txt的内容 使=本田|模型=公民|的color = red 使=丰田|模型=花冠|颜色=蓝色

new_rec = “作出=本田|模型=公民|颜色=蓝色”

$ sed -e“s / ^ make = honda。* / $ new_rec / g”temp.txt 使=本田|模型=公民|颜色=蓝色 使=丰田|模型=花冠|颜色=蓝色

希望这会有所帮助