$ awk -v OFS=',' '/^Name/ { if (line != "") print line; line = $0; next } { line = line OFS $0 } END { if (line != "") print line }' file
Name= Garen,Class= 9C,School= US
Name= Lulu,Class= 4A
Name= Kata,Class= 10D,School= UK
With the updated input in the question, this produces
Name= Garen,Class= 9C,Last Name= Wilson ,School= US,
Name= Lulu,Class= 4A,Last Name= Miller,
Name= Kata,Class= 10D,School= UK,Last Name= Thomas
If you want to delete the Last Name
bit, ignore it explicitly in the awk
code:
$ awk -v OFS=',' '/^Last Name/ { next } /^Name/ { if (line != "") print line; line = $0; next } { line = line OFS $0 } END { if (line != "") print line }' file
Name= Garen,Class= 9C,School= US,
Name= Lulu,Class= 4A,
Name= Kata,Class= 10D,School= UK
The awk
code, as a freestanding awk
program with comments:
BEGIN {
# Set output field separator to a comma.
# This can also be done with -v OFS="," on the command line.
OFS = ","
}
/^Last Name/ {
# Ignore these lines
next
}
/^Name/ {
# A line starts with "Name".
# Print the accumulated line and reset the line variable.
# Continue immediately with next line of input.
if (line != "")
print line
line = $0
next
}
{
# Accumulate lines in the line variable.
# Delimit each input data with OFS (a comma).
line = line OFS $0
}
END {
# Print the last accumulated line.
if (line != "")
print line
}
With sed
(this is an almost identical solution from an answer to another question)
/^Last Name/ d; # ignore these lines
/^Name/ b print_previous; # print previous record
H; # append this line to hold space
$ b print_previous; # print previous (last) record
d; # end processing this line
:print_previous; # prints a record accumulated in the hold space
x; # swap in the hold space
/^$/ d; # if line is empty, delete it
s/\n/,/g; # replace embedded newlines by commas
# (implicit print)
Running it:
$ sed -f script.sed file
Name= Garen,Class= 9C,School= US
Name= Lulu,Class= 4A
Name= Kata,Class= 10D,School= UK
Last Name
should be removed? – Kusalananda Dec 18 '18 at 07:38