I am looking for advice on how to search a part of a string within a file and replace the complete line OR append that string to that file if not found. I "played" with sed for a while now, but couldn't get it to work as expected.
I need to add:
/swapfile none swap sw 0 0
to /etc/fstab
(on Ubuntu 14.04 - Trusty Tahr).
Conditions:
- If any line starting with
/swapfile
is present in/etc/fstab
, remove that line and replace with the string provided above - If more than one line starting with
/swapfile
is found, remove them all and append the string above to the end of the file - If no
/swapfile
is present in/etc/fstab
, append the string to/etc/fstab
- The command must not show console output and must be a "one-liner" (due to automation purposes with puppet)
I am confident that's possible, but I simply didn't find a related tutorial about using sed in the way I need it.
I used sudo sed -i '$a/swapfile none swap sw 0 0' /etc/fstab
but this only appends the string :(