简体   繁体   English

在linux中查找字符串并替换行

[英]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". 我需要一个脚本,可以找到带有“volume = xxx”的文本行,然后将其替换为“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. @ jliu83,对正则表达式做一些阅读。 It'll make the pattern matching in the sed commands more understandable. 它将使sed命令中的模式匹配更容易理解。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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