I can't find a suitable sed expression to remove a word followed by a line return (\n)
Test file is:
line1\n
line2\n
line3mark\n
line4\n
line5\n
and i want to remove all occurances of mark\n leaving, in this case:
line1\n
line2\n
line3line4\n
line5\n
have searched and can use:
sed 's/\n//g' test.file to remove ALL \n's
but
sed 's/mark\n//g' test.file does not work
Strangely, s/mark\n//g does seem to work ok in vi in interactive mode.
Any help greatly appreciated! I would like to understand how to do it using SED if possible as I am sure it is possible!! However, if it can be done another way then I'm also happy as long as its on the command line as it has to run over many files.
Many thanks.
unix is a powerful. Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
sed reads input text from files or stdin, then edits the text line by line according to the provided conditions and commands. After sed performs the specified operation on each line, it outputs the processed text to stdout or a file, then moves on to the next line.
Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With