简体   繁体   中英

Find string and replace line in linux

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.

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

有了sed,你可以说:

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

将内容传递给此命令:

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

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

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM