The sed utility is most often used to search and replace patterns in text. It works like a text filter or a stream editor.
Syntax:
sed [options] ´command’ Input-File
Options:
-n No print. The default is to print all lines plus lines selected with the p
command.
-e The next command is an edit command; used for multiple edits.
-f sed commands are in a file.
FINDING TEXT USING SED
Using line numbers: singly or in a range.
Using Regular Expressions
Examples:
x Where x is a line number
x,y In a range of lines, from x to y
/pattern/ Where pattern is a regex
/pattern/pattern/ Choice of patterns
/pattern/,x Look for the pattern on this line
x,/pattern/ Look only at line x for the pattern
x,y! Not lines x to y
Basic sed editing commands
p – Print the matched lines
= – Display the line number of the file
a\- Append the text after the addressed line
i\-Insert new text after the addressed line
d – Delete addressed lines
c – Replace addressed text with new text
s – Substitute pattern with replacement pattern
r – Read text from another file
w – Write text to file
q – Quit after first pattern has been matched, or just quit
l – Show control characters in their octal ASCII equivalent
()-Group a series of commands to be performed only on addressed lines
n – Read the next line of text from another file and append it
g – Paste the contents of pattern2 into pattern1
y – Translate characters
n – Append next input line; this allows pattern matching across two lines
Examples:
Substitute teh to the globally: sed 's/teh/the/g' sample.txt Substitute teh to the on all lines: sed 's/teh/the/' sample.txt Print line 3: sed -n '3p' foo.txt Print lines 5 to 8: sed -n '5,8p' foo.txt Print lines with the word four: sed -n '/four/p' foo.txt Search for four in line 4: sed -n '4,/four/p' foo.txt Print lines containing $100: sed -n /\$100/p' foo.txt Print 10th line to the last: sed -n '10,$p' Print lines with ing: sed -n '/ing/p' Print the line number of a match: sed -n '/funny/=' foo.txt Print the line and line number: sed -n -e '/fun/p' -e '/fun/=' foo.txt Delete all commented lines: sed ‘/^#/ d ’ sample
More on sed!!!
sed can be used to append text. Let’s say we have a text on foo.txt file and a script on my.script file.
cat foo.txt 1 one 2 two 3 three 4 four cat my.script /four/p /four/a\ 5 five
Using my.script on foo.txt appends 5 five.
sed -n -f my.script foo.txt Output: 1 one 2 two 3 three 4 four 5 five
Writing a sed script
#!/bin/sed -f
/two/ a\
2.1
This script appends 2.1 after the word two on a file. After creating the script, make the script executable: chmod +x or chmod u+x insert.sh.
Running the sed script:
./insert foo.txt cat foo.txt 1 one 2 two 2.1 3 three 4 four 5 five
Take note of the dot-slash(./) symbol. ./ means in this directory, run the executable.
a\ is to append a string on a file file after a defined pattern. Using a\ on sed script works the same with i\. i\ is used to insert a string before the defined pattern.