Sed - Samples

Samples

To delete any line containing the word "yourword" from the file "yourfile":

sed '/yourword/d' yourfile

To delete all instances of the word "yourword":

sed 's/yourword//g' yourfile

To delete two words from a file simultaneously:

sed -e 's/firstword//g' -e 's/secondword//g' yourfile

or

sed 's/firstword//g;s/secondword//g' yourfile

In the next example, sed, which usually only works on one line, removes newlines from sentences where the second sentence starts with one space. Consider the following text:

This is my cat my cat's name is betty This is my dog my dog's name is frank This is my fish my fish's name is george This is my goat my goat's name is adam

The sed script below will turn it into (Note the output it affects only the lines that start with a space):

This is my cat my cat's name is betty This is my dog my dog's name is frank This is my fish my fish's name is george This is my goat my goat's name is adam

Here's the script:

sed 'N;s/\n / /;P;D;'
  • (N) add the next line to the work buffer
  • (s) substitute
  • (/\n /) match a newline character and a " ": find a new line followed by a space
  • (/ /) replace with: one space
  • (P) print the top line of the work buffer
  • (D) delete the top line from the work buffer and run the script again


Less portable but more complex sed usage is transposing an XML table into a CSV:

sed -rn '{s/ *//g;//{s/.*//g;H};//{s/<\/*field>//g;H};/<\/row>/{x;s/^\r*\n//;s/\r*\n\r*/","/g;s/^(*)/"\1"/;p};/First clear out all the extraneous whitespace:

s/ *//g

If the current line is a blank line, add a blank line to the hold space:

//{s/.*//g;H}

If there is an actual value in the field, strip the xml and add the value to the hold space:

//{s/<\/*field>//g;H}

If it is the end of a row (), then get the hold space, replace the newlines with '","', add quotes to the beginning and end and then print the line:

/<\/row>/{x;s/^\r*\n//;s/\r*\n\r*/","/g;s/^(*)/"\1"/;p}

If it is the beginning of a row, clear the hold space by adding a blank line:

/

Read more about this topic:  Sed

Famous quotes containing the word samples:

    Good government cannot be found on the bargain-counter. We have seen samples of bargain-counter government in the past when low tax rates were secured by increasing the bonded debt for current expenses or refusing to keep our institutions up to the standard in repairs, extensions, equipment, and accommodations. I refuse, and the Republican Party refuses, to endorse that method of sham and shoddy economy.
    Calvin Coolidge (1872–1933)