使用 sed 移动文本文件中的匹配行 [英] Moving matching lines in a text file using 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:
/SRC_OUT_DIR/{t=$0;next}
: 如果该行包含匹配SRC_OUT_DIR
的子字符串,则将该行存储在变量t
并移动到next
行(不执行 2 和 3)1
:默认操作:打印行/DEFAULTS/{print t}
: 如果当前行包含子字符串DEFAULTS
,则打印存储在变量中的行
/SRC_OUT_DIR/{t=$0;next}
: if the line contains a substring matchingSRC_OUT_DIR
, then store the line in a variablet
and move to thenext
line (don't execute 2 and 3)1
: default action: print the line/DEFAULTS/{print t}
: if the current line contains the substringDEFAULTS
, print the line stored in variablet
如果您要移动多行(这只向下移动):
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屋!