使用 sed 移动文本文件中的匹配行 [英] Moving matching lines in a text file using sed

查看:62
本文介绍了使用 sed 移动文本文件中的匹配行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注帖子

如何使用正则表达式匹配(bash脚本)将文件中的指定行移动到其他地方?

到我的示例文件

asdasd0
-SRC_OUT_DIR = /a/b/c/d/e/f/g/h
asdasd2
asdasd3
asdasd4
DEFAULTS {
asdasd6

最终输出应该是这样的

asdasd0
asdasd2
asdasd3
asdasd4
DEFAULTS {
-SRC_OUT_DIR = /a/b/c/d/e/f/g/h
asdasd6

我已经尝试了以下

sed "/-SRC_OUT_DIR.*/d;/DEFAULTS { /a"$(sed -n '/-SRC_OUT_DIR.*/p' test.txt)  test.txt`

但它不起作用.我得到以下输出

but it is not working. I get the following output

sed:can't read =: No such file or directory
sed:can't read "/a/b/c/d/e/f/g": No such file or directory
asdasd0
asdasd2
asdasd3
asdasd4
DEFAULTS {
-SRC_OUT_DIR
asdasd6

我也想知道为什么不能用\1,\2来打印需要移动的行.我试过了,但它什么也没打印.如果我需要将多个匹配的行移动到文件中的不同位置,我将如何编写 sed 命令?

I am also wondering why can't I use \1, \2 to print the line that needs to be moved. I tried that but it prints nothing. How would I write a sed command if I need to move multiple matching lines to different places in the file?

推荐答案

当您询问 sed 解决方案时,我建议为此使用 awk.不推荐使用大量 sed 命令的丑陋嵌套.尤其是因为您阅读了两次文件.

While you ask a sed solution I would propose to use awk for this. Using an ugly nesting of a multitude of sed commands is not really recommended. Especially because you read your file twice.

这是一个awk

awk '/SRC_OUT_DIR/{t=$0;next}1;/DEFAULTS/{print t}' file

它是如何工作的?

awk 将逐行读取您的 file.每行,它将一个接一个地执行以下三个命令:

awk will read your file line by line. Per line, it will do the following three commands one after the other:

  1. /SRC_OUT_DIR/{t=$0;next}: 如果该行包含匹配 SRC_OUT_DIR 的子字符串,则将该行存储在变量 t 并移动到 next 行(不执行 2 和 3)
  2. 1:默认操作:打印行
  3. /DEFAULTS/{print t}: 如果当前行包含子字符串DEFAULTS,则打印存储在变量中的行
  1. /SRC_OUT_DIR/{t=$0;next}: if the line contains a substring matching SRC_OUT_DIR, then store the line in a variable t and move to the next line (don't execute 2 and 3)
  2. 1: default action: print the line
  3. /DEFAULTS/{print t}: if the current line contains the substring DEFAULTS, print the line stored in variable t

如果您要移动多行(这只向下移动):

If you have multiple lines to move (this only moves downwards):

awk '/pattern1/ {t[1]=$0;next}
     /pattern2/ {t[2]=$0;next}
     /pattern3/ {t[3]=$0;next}
     /target3/ { print t[3] }
     1
     /target1/ { print t[1] }
     /target2/ { print t[2] }' file

注意pattern3会在target3之前打印.

这篇关于使用 sed 移动文本文件中的匹配行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆