If the pattern matches the newline on this line

Let's say the template is the string "Love"

input

This is some text Love this or that He is running like a rabbit 

Exit

 This is some text Love this or thatHe is running like a rabbit 

I noticed that sed is very annoying to remove newlines, any idea?

+7
grep awk sed tr
source share
5 answers

You can use this:

 sed '/^Love/{N;s/\n//;}' love.txt 

Details:

/^Love/ identifies the line to process if you like to use /[Ll]ove/ instead

N adds the following line to the pattern space. After this command, the template space contains Love this or that\nHe is running like a rabbit

s/\n// replace newline character

+12
source share

Perl:

 $ perl -pe 's/^(Love[^\n]*)\n/\1/' file.txt This is some text Love this or thatHe is running like a rabbit 

Or, if the target focuses only on \n , you can chomp based on the pattern:

 $ perl -pe 'chomp if /^Love/' file.txt This is some text Love this or thatHe is running like a rabbit 
+2
source share
 $ awk '/Love/{printf "%s ",$0;next} 1' file This is some text Love this or that He is running like a rabbit 

Explanation:

  • /Love/{printf "%s ",$0;next}

    For lines containing Love , the line is printed via printf without a new line. awk then starts with the line next .

  • 1

    For lines that do not include Love , they print normally (with a new line). Command 1 is an awk cryptographic abbreviation for printing normally.

+1
source share

Via Perl,

 $ perl -pe 's/^Love.*\K\n//' file This is some text Love this or thatHe is running like a rabbit 

\K discards previously matched characters.

OR

 $ perl -pe '/^Love/ && s/\n//' file This is some text Love this or thatHe is running like a rabbit 

If the line begins with the line Love , it removes the newline character from this line.

+1
source share

Here is another awk option:

 awk '{ORS=(/Love/?FS:RS)}1' file This is some text Love this or that He is running like a rabbi 

This will change the template based ORS


Here are some other awk

 awk '{printf "%s%s",$0,(/Love/?FS:RS)}' file This is some text Love this or that He is running like a rabbit 

If the string Love uses FS as a delimiter, use RS

This should work too, but use the first one.

 awk '{printf "%s"(/Love/?FS:RS),$0}' file 
+1
source share

All Articles