简体   繁体   English

重击:查找匹配的文本并替换下一行

[英]Bash: Find matching text and replace next line

Alert: I have seen these sort of questions before on stackoverflow. 警报:在stackoverflow上,我已经看到过这类问题。 I searched a lot. 我搜了很多。 Followed solutions but could not solve the problem. 已遵循解决方案,但无法解决问题。

I have a variable $NEW_FILE which gives a value of nothing(./location/file1)] when you do echo $NEW_FILE 我有一个变量$ NEW_FILE ,当您回显$ NEW_FILE时,该变量的值不为( ./location/file1 )]

I have a file test1.txt which contains: 我有一个文件test1.txt,其中包含:

Hello, World! 你好,世界!

This is not working 这不行

I don't know a thing about sed and awk 我对sed和awk一无所知

Now I want to search for word - working and add a new line after that contained in $NEW_FILE So desired output would be: 现在我要搜索单词-工作并在$ NEW_FILE中包含的行之后添加新行,因此所需的输出将是:

Hello, World! 你好,世界!

This is not working 这不行

nothing(./location/file1)] 什么都没有(./location/file1)]

I don't know a thing about sed and awk 我对sed和awk一无所知

How do i achive this in a bash using sed or awk? 我如何使用sed或awk快速实现此目标?

This is what i tried: awk '/working/ { print; 这就是我尝试过的:awk'/ working / {print; print $NEW_FILE; 打印$ NEW_FILE; next}1' test1.txt 下一个} 1'test1.txt

This gives output: 这给出了输出:

Hello, World! 你好,世界!

This is not working 这不行

$NEW_FILE $ NEW_FILE

I don't know a thing about sed and awk 我对sed和awk一无所知

Can someone help me with this? 有人可以帮我弄这个吗?

I think we also have to consider the forward and backward slashes in NEW_FILE variable. 我认为我们还必须考虑NEW_FILE变量中的正斜杠和反斜杠。

Your NEW_FILE is probably a bash-variable and therefore not a variable in awk. 您的NEW_FILE可能是bash变量,因此不是awk中的变量。 So, either let bash do the expansion: 因此,让bash进行扩展:

awk '/working/ { print; print "'$NEW_FILE'"; next}1' test1.txt

or pass/set the variable from the command line: 或从命令行传递/设置变量:

awk -v NEW_FILE="$NEW_FILE" '/working/ { print; print NEW_FILE; next}1' test1.txt

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

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