Concatenating lines with sed

An example of how you can concatenate lines from an input file using the sed command line tool.

Suppose you have the following file:


And you want to transform it into the following:

AA; 123
BB; 456
CC; 789

This can easily be achieved by using the Linux command sed. However, putting all transformation code on the command line might be a bit complex, therefore I created a sed script. The script looks as follows:

/^[[:alpha:]][[:alpha:]]$/ {
  s/^\(.*\)\n\(.*\)$/\1; \2/

When the input text is saved in a file with name input.txt and the script with name script.sed, then you should execute sed as follows:
sed -n -f script.sed input.txt

The sed script is a fact fairly easy to understand. On the first line we match every line that consists of 2 alphabetic characters. When we have such a match, the lines 2, 3 and 4 will be executed. On line 2 we read the next line of the file and append it to the currently read line. On line 3, we remove the newline character from the input and replace it with the dot-comma followed by a space. On line 4, we print the text.


You might also be interested in...