SED - removing string followed by LineFeed (\n) SED - removing string followed by LineFeed (\n) unix unix

SED - removing string followed by LineFeed (\n)


This should do the trick:

sed -i ':a;N;$!ba;s/mark\n//g' file

Explanation:

;    command separator within sed:a   a label, like in C/C++N    appends the next line to the pattern space$!ba repeats the N command for all lines but the last line

sed proceeds like this. it reads the standard input into the pattern space, performs a sequence of editing commands on the pattern space, then writes the pattern space to STDOUT.

When you do something like

sed -i 's/mark\n//' file

lines are copied to the pattern space one by one.

:a;N;$!ba appends each line to the pattern space.

Then the pattern space can be processed in one pass, removing any mark\n , the g option, for global, is important here because it ask sed not to stop at the first matching pattern.


For real line feeds, use:

sed -e ':a; /mark$/ { N; s/mark\n//; ba; }'

All lines that end with mark are joined with the next and the now middle \n is removed.

If there is a literal string \n at the end of the line, you need to escape the \ as \\n.


I saw awk tag, so here we go.

If \n is a 'line return', awk can join a line ending with a 'mark' with the next line.

$> awk '/mark$/ { sub(/mark$/,""); getline t; print $0 t; next }; 1' ./text line1line2line3line4line5