Sunday, January 28, 2024

[SOLVED] Sed line when matching some string and not another one with sed

Issue

Struggling again.

I would like to add a line right after another one when matching some pattern and not a another one.

Here's my input file :

# abc def hello
# bye hello zzzz
# abc def hello

Expected output is :

# abc def hello
new line
# bye hello zzzz
# abc def hello
new line

I want to add a line after any line of a file that starts with #, contains the word hello but not bye

I read about some exclusion possibility with sed (i.e \*<kbd>/pattern/!</kbd> \*) but haven't managed to add it to command so far.

Thanks!

sed -e '/^#.\*hello.\*/Ia\\'"new line" $input_file

where can the /bye/! thingy be included to this?


Solution

where can the /bye/! thingy be included to this?

Sed is a programming language, technically. Start a block and check within.

The real issue is that a reads the whole next line. So you have to like start another one to close }.

sed -e '/^#.*hello.*/I{ /bye/!a\' -e "new line" -e '}' "$input_file"

The syntax of a command is:

a\
text

Technically, there has to be newline in the sed script for text. I see a\text works anyway, but technically it is not valid. GNU sed also allows for just a text.

Prefer to quote variable expansion in shell. Check your scripts with shellcheck.



Answered By - KamilCuk
Answer Checked By - David Goodson (WPSolving Volunteer)