Tag Archives: text manipulation

How to combine X consecutive lines in one using sed

It happens that you have a list and you’d like to combine multiple lines in one.
For example, a list like this one:

Mark
Smith
London
Sarah
Ruffle
Glasgow
Paul
Thompson
Liverpool
....

And have something like that:

Mark - Smith - London
Sarah - Ruffle - Glasgow
Paul - Thompson - Liverpool

How to achieve it?

Use this command:

sed 'N;N;s/\n/ - /g' list.txt

Use one extra “N” for every line you want to merge. It’s like (N-1). So, if you want to merge 3 lines like in this example, you need 2 N’s. If you’d like to merge 2 lines, you just need 1 N, and so.

Happy merging 🙂