Search for specific line of text file, replace up

2019-08-07 02:50发布

问题:

In file my_file.ini, I want to modify the line starting with dataspecs like so:

replace dataspecs old_val old stuff blah blah ! blah blah with

dataspecs $new_val ! blah blah, where new_val is a bash variable, and everything after the ! is preserved. Also, I don't know the value of old_val.

I don't care whether it's sed or awk or just bash, I'm just looking for a simple answer that I can understand. I would really appreciate a solution, especially if you could explain what the code of the solution means, for someone who is just learning sed and awk (not the easiest code to look at). Thanks!

回答1:

Use sed:

sed -i.bak "s/^\( *dataspecs \)[^\!]*/\1${new_val} /" my_file.ini

PS: I am using inline flag -i of sed for inline editing, this will save the modified file.



回答2:

I'd suggest this form of sed:

sed "s/^\\(dataspecs \\)[^!]*\\( !.*\\)/\\1${new_val}\\2/" my_file.ini

Add -i option if you want to modify the file directly.

sed -i "s/^\\(dataspecs \\)[^!]*\\( !.*\\)/\\1${new_val}\\2/" my_file.ini


回答3:

awk '/dataspecs old_val/ {$2="$new_val"}1' my_file.ini