linux - 如何使用 sed 或其他 linux 工具有条件地交换两行?

标签 linux bash sed

我想交换两行,但前提是它们的顺序错误。例如,如果我有这样的 XML 行(文件中的任何位置,某些位置不需要):

<person>
    <given-name>John</given-name> 
    <surname>Smith</surname>
</person> 

我想交换第二行和第三行,以便它产生

<person>
    <surname>Smith</surname>
    <given-name>John</given-name> 
</person> 

但仅适用于那些行乱序的文件。有没有办法用 sed 或其他 linux 工具来做到这一点?

最佳答案

这可能对你有用(GNU sed);

sed -r '$!N;s/^(\s*<given-name>.*)\n(\s*<surname>.*)/\2\n\1/;P;D' file

一次读取 2 行,如果组合错误则换行。

关于linux - 如何使用 sed 或其他 linux 工具有条件地交换两行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23253695/

相关文章:

linux - bash:当它是进程重定向的结果时执行 $0

linux - debootstrap 失败并显示 "Failed to retrieve InRelease"

bash - 如何在 Bash 中将字符串拆分为多行?

正则表达式删除字符串的中间部分并向前看

macos - sed: c 命令,只改变第一行,文本被删除

html - 如何使用 vim 和插件快速为所有行添加 html 属性和值?

linux - 无法挂载 VMware 共享文件系统

linux - 套接字绑定(bind)在一个端口上,但 netstat 和 lsof 等工具显示它在其他端口上监听

linux - 如何使用ssh heredoc在bash中删除多个文件?

bash - git 别名可以像 bash 别名一样扩展吗?