Shell Programming Blog Shell Programming Blog

Wednesday, 31 October 2012

Linux Bash Scripting: How to combine two lines by removing newline character using sed

Unknown | 08:57 | | Be the first to comment!

Bash Linux Unix shell scripting

In this post we will see how to remove the newline character and combine two lines in a text file using "sed".

In sed, we have single line version and multi-line version of few commands. One such command is the next command. Click here to see an example for single-line version of next command in sed.

You might want to look at :

The processing space of the sed editor is known as the pattern space. The multi-line next command (N) adds the next line to the existing pattern space which already contains the previous line. So, the sed editor can treat two lines as a single line. Below is an example for the N command.

 

The above sed editor script searches for the line of text that contains the word “first” in it. When it finds the line, it uses the N command to combine the next line with that line. It then uses the substitution command (s) to replace the newline character with a space. The result is that the two lines in the text file appear as one line in the sed editor output.

Sunday, 28 October 2012

Linux Bash Scripting: How to remove a blank line after a particular line using sed

Unknown | 07:35 | | Be the first to comment!

Bash Linux Unix shell scripting
Removing a blank line after a particular line can be achieved using the single-line next command (n) of the sed editor.

The lowercase n command tells the sed editor to move to the next line of text in the data stream, without going back to the beginning of the sed commands. Normally the sed editor processes all of the defined commands on a line before moving to the next line of text in the data stream. The single‐line next command alters this flow.

In the below example, the data file that contains five lines, two of them empty. The goal is to remove the blank line after the header line but leave the blank line before the last line intact. If you write a sed script to just remove blank lines, you will remove both blank lines.

 

This happened because there was no specific way to find the unique blank line that you wanted to delete. The same can be achieved using the n command as shown in the below script.


The above script searches for the keyword "header" and then moves to the next line when it executes the n command and then applies the d command to delete the blank line below it.

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming