Mike Fry
Mike Fry

Reputation: 33

With sed or awk, move line matching pattern to bottom of file

I have a similar problem. I need to move a line in /etc/sudoers to the end of the file.

The line I am wanting to move:

#includedir /etc/sudoers.d

I have tried with a variable

#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

Not getting any errors nor the result I am looking for.

Any suggestions?

Upvotes: 2

Views: 1103

Answers (4)

potong
potong

Reputation: 58488

This might work for you (GNU sed):

sed -n '/regexp/H;//!p;$x;$s/.//p' file

This removes line(s) containing a specified regexp and appends them to the end of the file.

To only move the first line that matches the regexp, use:

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

This uses a loop to read/print the remainder of the file and then append the matched line.

Upvotes: 1

kvantour
kvantour

Reputation: 26521

If you have multiple entries which you want to move to the end of the file, you can do the following:

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

or

sed -n '/regex/!{p;ba};H;:a;${x;s/.//;p}' file

Upvotes: 0

Thor
Thor

Reputation: 47189

You could do the whole thing with sed:

sed -e '/#includedir .etc.sudoers.d/ { h; $p; d; }' -e '$G' /etc/sudoers

Upvotes: 1

JNevill
JNevill

Reputation: 50218

With awk:

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

That says:

  1. If the line $0 is "#includedir /etc/sudoers.d" then set the variable lastline to this line's value $0 and skip to the next line next.
  2. If you are still here, print the line {print $0}
  3. Once every line in file is processed, print whatever is in the lastline variable.

Example:

$ 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

Upvotes: 3

Related Questions