Search for specific line of text file, replace up

2019-08-07 02:14发布

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!

3条回答
走好不送
2楼-- · 2019-08-07 02:44

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-08-07 02:53
awk '/dataspecs old_val/ {$2="$new_val"}1' my_file.ini
查看更多
女痞
4楼-- · 2019-08-07 03:06

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
查看更多
登录 后发表回答