0

My /etc/sudoers file contain entries as below. Through sed, I want to insert a new entry for a new file after the first entry(filename can be anything) as below and save the file.

Now:

#
# Many Line before
#include /etc/sudoers.d/file1
#include /etc/sudoers.d/file2
#include /etc/sudoers.d/file3
#include /etc/sudoers.d/file4
#include /etc/sudoers.d/file5
#include /etc/sudoers.d/file6
# Many lines after

Goal:

#
# Many Line before
#include /etc/sudoers.d/file1
#include /etc/sudoers.d/newfile
#include /etc/sudoers.d/file2
#include /etc/sudoers.d/file3
#include /etc/sudoers.d/file4
#include /etc/sudoers.d/file5
#include /etc/sudoers.d/file6
# Many lines after

I tried like this but it inserts for each existing entries.

sed '/include \/etc\/sudoers.d/a #include /etc/sudoers.d/newfile' /etc/sudoers

NOTE: I tried other answers to similar questions, but all are inserting new line for each match.

itsraja
  • 1,640
  • 4
  • 32
  • 48
  • try adding `\/file1$` to the current search regex.. you could also use another delimiter like `\|regex|a ...` to avoid all the `\/` ... and probably won't make a difference, but you need `\.` to match `.` literally – Sundeep Sep 20 '20 at 15:15
  • Use `#includedir /etc/sudoers.d`. See `man 5 sudoers`. – Cyrus Sep 20 '20 at 15:16
  • @Sundeep file1 need not be there, it could be any name. But #include /etc/sudoers.d will be there. – itsraja Sep 20 '20 at 15:22
  • Does this answer your question? [Insert line after first match using sed](https://stackoverflow.com/questions/15559359/insert-line-after-first-match-using-sed) – Ravi Saroch Sep 20 '20 at 15:24
  • @RaviSaroch I already referred it. It inserts for each occurrence. – itsraja Sep 20 '20 at 15:29
  • @Cyrus My file does not contain #includedir /etc/sudoers.d. Policy it seems. – itsraja Sep 20 '20 at 15:35
  • See: [sed to insert on first match only](https://stackoverflow.com/q/9970124/3776858) – Cyrus Sep 20 '20 at 15:52
  • @itsraja, then I'd suggest `awk '1; !f && index($0, "#include /etc/sudoers.d/"){f=1; print "#include /etc/sudoers.d/newfile"}'` – Sundeep Sep 21 '20 at 03:01

0 Answers0