Replace Line Breaks on matching lines, using AWK

awkcommand linesed

I have the following data

What i'd like to do is for every line, where there is no ,"555" at the end, I want to remove the the line break, \n, and replace it with space.

So, the 'matching line' would be the line without the "555" at the end. i'd want to replace the line break from those lines.

I am limited in that I can't use Perl for this. So, it has to be AWK, or SED. But preferably AWK as I know SED isn't that good for working on multiple lines.

Here are 2 examples:

Example 1

"abc","555"
"d
e
f","555"
"xyz","555"
"abc
d,e,f ghi
jkl
mnop,qrs","555"

Should become (after amendment)

"abc","555"
" d e f","555"
"xyz","555"
"abc d,e,f ghi jkl mnop,qrs","555"

& Example 2

"abc","555"
"d
e
f","555"
"xyz","555"
"aa
bb
cc
dd","555"

Should become (after amendment)

"abc","555"
"d e f","555"
"xyz","555"
"aa bb cc dd","555"

So in output needed, actually every line has format of

"content","555"

Best Answer

The trick, in this case, is not to think of it as “working on multiple lines”.

awk '/"555"$/ {print; next} {printf "%s ", $0}'

prints each line that is the last line of a group normally, and then says next to go on to the next input line (not processing the remaining command).  The remaining command, which becomes a default case, prints the current line, followed by a space, without a newline.  This could also be done as

awk '{if ($0 ~ /"555"$/) print; else printf "%s ", $0}'
Related Question