Issue
I am trying to add a prefix to all the lines in a file that don't start with one of multiple words using sed.
Example :
someText
sleep 1
anotherString
sleep 1
for i in {1..50}
do
command
sleep 1
secondCommand
sleep 1
done
Should become
PREFIX_someText
sleep 1
PREFIX_anotherString
sleep 1
for i in {1..50}
do
PREFIX_command
sleep 1
PREFIX_secondCommand
sleep 1
done
I am able to exclude any line starting with a single pattern word (ie: sleep, for, do, done), but I don't know how to exclude all lines starting with one of multiple patterns. Currently I use the following command :
sed -i '/^sleep/! s/^/PREFIX_/'
Which works fine on all the lines starting with sleep. I imagine there is some way to combine pattern words, but I can't seem to find a solution. Something like this (which obviously doesn't work) :
sed -i '/[^sleep;^for;^do]/! s/^/PREFIX_/'
Any help would be greatly appreciated.
Solution
Use alternation with multiple words for negation:
sed -i -E '/^(sleep|for|do)/! s/^/PREFIX_/' file
PREFIX_someText
sleep 1
PREFIX_anotherString
sleep 1
for i in {1..50}
do
PREFIX_command
sleep 1
PREFIX_secondCommand
sleep 1
done
/^(sleep|for|do)/!
will match all lines except those that start with sleep
, or for
or do
words.
Answered By - anubhava Answer Checked By - David Marino (WPSolving Volunteer)