从变量替换整行获取数字

时间:2014-09-24 17:39:59

标签: sed

我有一个特定行的文件,让我们说......

AAA BBB CCC

我需要在找到之后替换整行,所以我做了:

q1=`grep -Hnm 1 "AAA" FILE | cut -d : -f 2`

它输出第一次出现的行号(在q1中),因为它有多次出现,现在,这里出现了我的问题......在上一步中我使用这个sed来替换某一行文件:

sed -e '3s/.*/WHATEVER/' FILE

要用WHATEVER替换(在示例中,第3行)整行,但现在如果我尝试使用$ q1而不是指示行号的“3”它不起作用:

sed -e '$q1s/.*/WHATEVER/' FILE

这可能是一个愚蠢的语法错误,欢迎任何帮助;提前谢谢

4 个答案:

答案 0 :(得分:0)

尝试: sed -e '${q1}s/.*/WHATEVER/' FILE

答案 1 :(得分:0)

我会使用awk:

awk '/AAA/ && !r {print "WHATEVER"; r=1; next} {print}' <<END
a
b
AAA BBB CCC
d
e
AAA foo bar
f
END
a
b
WHATEVER
d
e
AAA foo bar
f

答案 2 :(得分:0)

如果要替换文件中第一次出现的字符串,可以使用此awk脚本:

awk '/occurrence/ && !f++ {print "replacement"; next}1' file

替换只会在第一次打印,因为!f++只会评估为真一次(在后续评估中,f将大于零,因此!f将为false。最后的1始终为true,因此对于匹配的每一行,awk执行默认操作并打印该行。

测试出来:

$ cat file
blah
blah
occurrence 1 and some other stuff
blah
blah
some more stuff and occurrence 2
blah
$ awk '/occurrence/ && !f++ {print "replacement"; next}1' file
blah
blah
replacement
blah
blah
some more stuff and occurrence 2
blah

可以通过以下方式轻松地将“replacement”字符串设置为shell变量的值:

awk -v rep="$r" '/occurrence/ && !f++ {print rep; next}1' file

其中$r是一个shell变量。

使用与上述相同的文件和评论中的示例变量:

$ q2="x=\"Second\""
$ awk -v rep="$q2" '/occurrence/ && !f++ {print rep; next}1' file
blah
blah
x="Second"
stuff
blah
blah
some more stuff and occurrence 2
blah

答案 3 :(得分:0)

sed "${q1} c\
WHATEVER" YourFile

但你可以直接使用

sed '/YourPatternToFound/ {s/.*/WHATEVER/
:a
N;$!ba
}' YourFile
相关问题