Sed and Awk

Sed and Awk

Posted by Deetch on June 23, 2017

sed

Basic sed syntax:
sed [options] {sed-commands} {input-file}


Basic sed syntax for use with sed-command file:
sed [options] -f {sed-commands-in-a-file} {input-file}

Basic sed syntax using -e:
sed [options] -e {sed-command-1} -e {sed-command-2} {input-file}

Basic sed syntax using { }:
sed [options] '{
sed-command-1
sed-command-2
11Sed and Awk 101 Hacks
}' input-file


-n
Print Pattern Space (p command)
Using the sed p command, you can print the current pattern space.

sed -n '1,4 p' employee.txt
print 1-4 lines,  ($ represents the last line)

sed -n '1,4 w output.txt' employee.txt


sed '[address-range|pattern-range] s/original-
string/replacement-string/[substitute-flags]' inputfile


sed '{
s/Developer/IT Manager/
s/Manager/Director/
}' employee.txt

Delete all the empty lines from a file:
sed '/^$/ d' employee.txt

Delete all comment lines (assuming the comment starts with
#):
sed '/^#/ d' employee.txt

command:
p:打印
d:删除
w:写文件



substitute command syntax:
sed 's/Manager/Director/' employee.txt

awk命令:

awk -Fs '/pattern/ {action}' input-file
(or)
awk -Fs '{action}' intput-file


Awk Program Structure (BEGIN, body, END
block)


awk 'BEGIN { FS=":";print "---header---" } \
/mail/ {print $1} \
END { print "---footer---"}' /etc/passwd
---header---
mail
mailnull
---footer---