linux - 在文件中搜索一行并将下一个模式匹配的行替换为 linux 中的换行符(Shell 脚本)

标签 linux shell awk sed grep

我有一个包含以下数据的文件。我们将其命名为 myfile.xml :

.........
<header>unique_name</header>
......
somelines
......
<version>I need only this line</version>
......
......
<version>This is second match of version, which I dont want</version>

现在我正在寻找执行以下操作的 linux 命令:

  1. 可以有很多<header>.*</header>线。但我需要 <header>unique_name</header> .这是一个唯一的 header 名称,我将对其进行硬核处理。它在文件中只出现一次,但可以出现在文件中的任何位置。

  2. 搜索 <version>.*</version>出现在 <header>unique_name</header> 之后在 myfile.txt 中,这应该替换为 <version>new version number</version> .

我试过使用 grep 来实现, sed , awk ,但我做不到。请指教。

输入和预期输出:

输入文件“myfile.xml”:

  • stringtoFIND= <header>unique_name</header>
  • newversionNUMBER=new_version_number

myfile.xml文件内容如下:

<header>Some strings</header>
......Somelines...........
<version>I dont need this line, since header doesnt match stringtoFIND variable</version>

<header>unique_name</header>
.............
<version>I need only this line</version>
...........
..........
<version>I Dont need this line</version>
.........

预期输出

<header>Some strings</header>
......Somelines...........
<version>I dont need this line, since header doesnt match stringtoFIND variable</version>

<header>unique_name</header>
.............
<version>new_version_number</version>
...........
..........
<version>I Dont need this line</version>
.........

最佳答案

对第三个参数使用 GNU awk 来匹配 ():

$ cat tst.awk
match($0,/<header>(.*)<\/header>/,a) {
    inBlock = (a[1] == "unique_name" ? 1 : 0)
}

inBlock && match($0,/(.*<version>).*(<\/version>.*)/,a) {
    $0 = a[1] "new_version_number" a[2]
    inBlock = 0
}

{ print }

$ awk -f tst.awk file
<header>Some strings</header>
......Somelines...........
<version>I dont need this line, since header doesnt match stringtoFIND variable</version>

<header>unique_name</header>
.............
<version>new_version_number</version>
...........
..........
<version>I Dont need this line</version>
.........

关于linux - 在文件中搜索一行并将下一个模式匹配的行替换为 linux 中的换行符(Shell 脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542537/

相关文章:

linux - 使用 "exec"命令行为从终端启动 Linux 图形应用程序

linux - 为什么 exec.Start() 创建的进程在其父进程被 SIGINT 杀死时退出?

python - OSX Automator 无法使用 shell 中的模块运行 Python 脚本

Bash:如何通过插入连续字符和换行符来查找和拆分长行?

linux - 使用 fping 提取平均时间

c - 如何在基于 Linux 的嵌入式设备上造成内存碎片?

c - 如何 "bypass"pthreads限制数量

linux - 如何在 shell 中剪切字符串的第一列(可变长度)

java - Android Shell 命令应该使用 Java 还是 Jni 运行

linux - 可变长度表的 Bash 列总和