Find string and replace line in linux

2019-05-17 17:28发布

问题:

I'd like to do the following, but I can't seem to find an elegant way to do it.

I have a text file that looks like this:

..more values
stuff = 23   
volume = -15
autostart = 12
more values..

Now the "volume" value may change, depending on the circumstance. I need a script that can find that line of text with "volume = xxx" then replace it with the line "volume = 0". What is an elegant solution to this? This line in the text is not guaranteed to be the first line, so I need a way to find it first.

回答1:

sed 's/^volume =.*/volume = 0/g' file.txt


回答2:

With sed you can say:

sed '/^volume/s/.*/volume = 0/' infile


回答3:

Pipe the contents into this command:

sed -e 's/^volume\s*=\s*-\?[0-9]\+$/volume = 0/'


回答4:

sed 's/^volume=\(.*\)$/volume=1/g' inputfile



回答5:

@jliu83, do some reading on regular expressions. It'll make the pattern matching in the sed commands more understandable.

http://en.wikipedia.org/wiki/Regular_expression