concatenate lines using shell scripting

Shell Programming and Scripting

Kindly Note - This is a Single User Post by Forum Member bakunin Regarding:
concatenate lines using shell scripting.
Please Follow The Primary Link Above to View the Full Discussion.

Old 09-06-2009
bakunin bakunin is offline Forum Staff  
Bughunter Extraordinaire
in sed it is easy: we have two types of lines, the ones reading "=" and the others. When we encounter a "="-line, we want to print out what we have so far, minus the newlines. If we encounter one of the other lines we want to store its contents until we encounter a "="-line.

sed has a so-called "hold space", think of it as a variable, where you can store things until you need them. We append everything to this hold space until we encounter a "="-line, then we recall the hold space, filter out all embedded newlines and print it, then start over.

In the following script i have put in comment for your understanding, remove them, because sed doesn't allow inline commenting in scripts. Furthermore, you can put the whole script on one line, replacing linefeeds with semicolons:

sed -n '/^=/ {                   # if a line starts with "="
          s/.*//                 # delete this lines content
          x                      # exchange the pattern space (empty) and the hold space
          s/\n//g                # delete newlines
          p                      # then print what you have
     /^=/ ! {                    # if a line doesn't start with "="
          H                      # append it to the hold space
     }' /your/file > newfile

for short:

sed -n '/^=/{s/.*//;x;s/\n//gp};/^=/!{H}' /your/file > newfile

I hope this helps.