Difference between revisions of "Sed"

From TBP Wiki
Jump to: navigation, search
(Using sed)
(Using sed)
 
(One intermediate revision by the same user not shown)
Line 14: Line 14:
 
This will append "BAR" to the end of every line in testfile3 and output to file testfile4
 
This will append "BAR" to the end of every line in testfile3 and output to file testfile4
 
     sed 's/$/"BAR/' testfile3 > testfile4
 
     sed 's/$/"BAR/' testfile3 > testfile4
 +
 +
Show only lines 12-18 of file.txt
 +
    sed -n 12,18p file.txt
 +
 +
Show all of file.txt except for lines from 12 to 18
 +
    sed 12,18d file.txt
 +
 +
Double-space file.txt
 +
    sed G file.txt
 +
 +
Print only lines with three consecutive digits
 +
    sed '/[0-9]\{3\}/p' file.txt
 +
 +
Delete all spaces in front of every line of file.txt
 +
    sed 's/^[ ^t]*//' file.txt
 +
 +
Delete all spaces at the end of every line of file.txt
 +
    sed 's/[ ^t]*$//' file.txt
 +
 +
Delete all spaces in front and at the end of every line of file.txt
 +
    sed 's/^[ ^t]*//;s/[ ^]*$//' file.txt
 +
 +
If a line contains baz, substitute foo with bar
 +
    sed '/baz/s/foo/bar/g' file.txt
 +
 +
Remove ":" from end of a line:
 +
    sed 's/:$//'

Latest revision as of 14:19, 18 December 2019

sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

Using sed

Sed can remove all instances of foo with bar with the following.

   cat report.txt | sed 's/foo/bar/g' > report_new.txt

This removed all lines containing "loopback" from FILENAME and outputs into newfile.txt

   sed '/loopback/d' ./FILENAME > newfile.txt

This will remove empty spaces from FILENAME.

   cat FILENAME | sed '/^$/d;s/blank://g'

This will append "BAR" to the end of every line in testfile3 and output to file testfile4

   sed 's/$/"BAR/' testfile3 > testfile4

Show only lines 12-18 of file.txt

   sed -n 12,18p file.txt

Show all of file.txt except for lines from 12 to 18

   sed 12,18d file.txt

Double-space file.txt

   sed G file.txt

Print only lines with three consecutive digits

   sed '/[0-9]\{3\}/p' file.txt

Delete all spaces in front of every line of file.txt

   sed 's/^[ ^t]*//' file.txt

Delete all spaces at the end of every line of file.txt

   sed 's/[ ^t]*$//' file.txt

Delete all spaces in front and at the end of every line of file.txt

   sed 's/^[ ^t]*//;s/[ ^]*$//' file.txt

If a line contains baz, substitute foo with bar

   sed '/baz/s/foo/bar/g' file.txt

Remove ":" from end of a line:

   sed 's/:$//'