Optimize shell script for multiple sed replacements

前端 未结 7 1899
清歌不尽
清歌不尽 2020-12-19 08:50

I have a file containing a list of replacement pairs (about 100 of them) which are used by sed to replace strings in files.

The pairs go like:



        
7条回答
  •  情歌与酒
    2020-12-19 09:14

    You can try this.

    pattern=''
    cat replacement_list | while read i
    do
        old=$(echo "$i" | awk -F'|' '{print $1}')    #due to the need for extended regex
        new=$(echo "$i" | awk -F'|' '{print $2}')
        pattern=${pattern}"s/${old}/${new}/g;"
    done
    sed -r ${pattern} -i file
    

    This will run the sed command only once on the file with all the replacements. You may also want to replace awk with cut. cut may be more optimized then awk, though I am not sure about that.

    old=`echo $i | cut -d"|" -f1`
    new=`echo $i | cut -d"|" -f2`
    

提交回复
热议问题