使用sed或awk,将行匹配模式移动到文件底部

使用sed或awk,将行匹配模式移动到文件底部,awk,sed,Awk,Sed,我也有类似的问题。我需要将/etc/sudoers中的一行移到文件的末尾 我想移动的线路: 包括IR/etc/sudoers.d 我试过使用一个变量 #creates variable value templine=$(cat /etc/sudoers | grep "#includedir /etc/sudoers.d") #delete value sed '/"${templine}"/d' /etc/sudoers #write value to the bottom of the

我也有类似的问题。我需要将/etc/sudoers中的一行移到文件的末尾

我想移动的线路:

包括IR/etc/sudoers.d 我试过使用一个变量

#creates variable value
templine=$(cat /etc/sudoers | grep "#includedir /etc/sudoers.d")

#delete value
sed '/"${templine}"/d' /etc/sudoers

#write value to the bottom of the file
cat ${templine} >> /etc/sudoers
没有得到任何错误,也没有得到我想要的结果

有什么建议吗?

关于awk:

awk '$0=="#includedir /etc/sudoers.d"{lastline=$0;next}{print $0}END{print lastline}' /etc/sudoers
也就是说:

如果行$0包含在dir/etc/sudoers.d中,则将变量lastline设置为此行的值$0,然后跳到下一行。 如果您仍在这里,请打印行{print$0} 处理完文件中的每一行后,打印lastline变量中的任何内容。 例如:

$ cat test.txt
hi
this
is
#includedir /etc/sudoers.d
a
test
$ awk '$0=="#includedir /etc/sudoers.d"{lastline=$0;next}{print $0}END{print lastline}' test.txt
hi
this
is
a
test
#includedir /etc/sudoers.d

你可以用sed来完成整个过程:


如果要将多个条目移到文件末尾,可以执行以下操作:

awk '/regex/{a[++c]=$0;next}1;END{for(i=1;i<=c;++i) print a[i]}' file

这可能适用于GNU sed:

sed -n '/regexp/H;//!p;$x;$s/.//p' file
这将删除包含指定regexp的行,并将它们追加到文件末尾

要仅移动与regexp匹配的第一行,请使用:

sed -n '/regexp/{h;$p;$b;:a;n;p;$!ba;x};p' file

这使用循环读取/打印文件的其余部分,然后附加匹配的行。

我正在使用/etc/sudoers的副本进行测试,得到的结果就像命令没有终止一样。awk'$0==includedir/etc/sudoers.d{lastline=$0;next}{print$0}END{print lastline}`/etc/sudoers>我的道歉。我已经更新了答案。我用反勾号代替了单引号。已更正。如果文件中不存在includedir/etc/sudoers.d怎么办?这会在includedir所在的位置留下一行空白;为了避免这种情况,请使用{h;d;}而不是x。@BenjaminW:这一点很好,并在模式位于最后一行时包含$p。如果regexp匹配多次,并且只移动最新的匹配项,则可能会减少文件。@potong:true,但鉴于此模式在这里是可取的特性
sed -n '/regexp/H;//!p;$x;$s/.//p' file
sed -n '/regexp/{h;$p;$b;:a;n;p;$!ba;x};p' file