Process text streams using filters: Sed

«« Previous
Next »»

LPIC-1 Using SED


The stream edit or sed is simply one of those Linux tools that you will love once you have a little practice and know the basic syntax. The uses are for system administration but equally can apply to any manipulation of text files.

sed [options] [address] [command] <input-file>

We start of seeing how we can emulate the command cat:

sed -n 'p' ntp.conf

The -n suppresses standard output and the command p print the pattern space. As we have not set any address range this will be all lines in the ntp.conf. As we address a range to it:

sed -n '1,2 p' ntp.conf

We would print just the first two lines, from lines 1 to line 2. Or:

sed -n '50,$ p' ntp.conf

Would print form line 50 to the end of the document. We would like to use sed to create a backup of the ntp.conf and edit the original to remove comments and blank lines:

sed -i.$(date +%F) '/^#/d;/^$/d' ntp.conf

The -i is the in-place edit but the prefix directly following tells sed to create a backup. In this case with a date extension (ntp.conf.date) We run two commands each with an address space, the first deletes the commented lines and the second, separated from the first by a semi-colon , deletes the bank lines.


«« Previous
Next »»

0 comments:

Post a Comment