How to Use sed to Merge Every Two Lines in File


Often you may want to use sed to merge every two lines in a file into one line.

You can use the following basic syntax to do so:

sed 'N;s/\n/ /' team_names.txt

This particular example merges every two lines in the team_names.txt file into one line.

Note that you can use the -i flag if you’d like to modify the file in-place:

sed -i 'N;s/\n/ /' team_names.txt

The following example shows how to use this syntax in practice.

Example: Use sed to Merge Every Two Lines in File

Suppose we have a text file named team_names.txt that contains the city names and team names of various basketball teams.

We can use the cat command to view the contents of this file:

Suppose that we would like to merge every two lines in the file into one line.

We can use the following syntax to do so:

sed 'N;s/\n/ /' team_names.txt

The following screenshot shows how to use this syntax in practice:

sed merge two lines into one

Notice that every two lines in the file has been merged into one line.

Each city is now listed on the same line as the appropriate team name.

Note that you could also use the following syntax to make this modification to the file in-place:

sed -i 'N;s/\n/ /' team_names.txt

This would make this modification to the team_names.txt file in-place.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Delete All Lines Containing Specific String
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply