我也有类似的问题。我需要在/etc/sudoer中将一行移至文件末尾。
我想移动的线:
#includedir /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
为"#includedir /etc/sudoers.d"
,则将变量lastline
设置为该行的值$0
,然后跳过下一行next
。 - 如果您还在这里,请打印行
{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
:
sed -e '/#includedir .etc.sudoers.d/ { h; $p; d; }' -e '$G' /etc/sudoers
这可能对您有用(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
这使用一个循环读取/打印文件的其余部分,然后附加匹配的行。
如果您有多个要移至文件末尾的条目,则可以执行以下操作:
awk '/regex/{a[++c]=$0;next}1;END{for(i=1;i<=c;++i) print a[i]}' file
或
sed -n '/regex/!{p;ba};H;:a;${x;s/.//;p}' file