another_file:
text from another file!
t_file:
a
bb
ccc
Joseph
joseph
last line
date: 12-11-2011
DATE:12/11/2011
1
2
3
4
5
11 --> 22
1110111
sed cmd:
#print out the lines matched
sed -n '/[jJ]oseph/p' t_file
#delete specified lines
sed '1,3d' t_file
#print last line
sed -n '$p' t_file
#print the matched lines
sed -n '/joseph/p' t_file
#print all lines, and print the matched lines twice.
sed '/joseph/p' t_file
#campare the result...
sed 's/[jJ]oseph/& Yang/g' t_file
sed -n 's/[jJ]oseph/& Yang/g' t_file
sed 's/[jJ]oseph/& Yang/gp' t_file
sed -n 's/[jJ]oseph/& Yang/gp' t_file
#analyze to the cmd above
sed -n 's/\([jJ]oseph\)/Yang \1/gp' t_file
#change the default delimiter
sed -n 's-1-2-gp' t_file
sed -n 's/1/2/gp' t_file
#print lines from '3' to '5'
sed -n '/3/,/5/p' t_file
sed -n '/3/,/5/s/$/###tail###/p' t_file
sed -e 's/11/%%/g' -e 's/\(%%\)/##\1##/pg' -n t_file
sed -e 's/11/%%/g' -e 's/\(%%\)/##\1##/p' -n t_file
#file reading
sed '/4/r another_file' t_file
#file writing
sed -n '/3/,/4/w file_write' t_file && cat file_write
#append operation
sed '/5/a \
---> append one line after <-----' t_file
#insert the contents before the specified line
sed '/5/i \
---> append one line before <-----' t_file
#change the contents
sed '/5/c \
---> change one line <-----' t_file
# 'n' cmd, sed command will applied to the matched line's next line
sed '/^date/ { n; s/\/2011$/\/change next line /p; }' t_file
# xhg char
sed 'y/01/xy/' t_file
#match the line has 'Joseph', change 'joseph' to 'hofrat'
# in the matched line's next line, and sed exit
sed '/Joseph/{ n; s/joseph/hofrat/; q ; }' t_file
#when read one line from the file, sed place the line to mode buffer(size 8192Bytes)
# and the sed command applied on this line.
# There exist another buffer named holding buffer(size 8192B)
# 'h' cmd will save the line in the mode buffer to the holding buffer.
# 'g' cmd will excute the oppsite operation.
sed -e '/DATE/ {h;d;}' -e '/11011/{g;}' t_file
sed -e '/DATE/ {h;d;}' -e '/11011/{x;}' t_file # 'g' or 'x'
# the cmd above, do the following operation:
# the line contains 'DATE' will firstly be placed to the mode buffer and then
# placed to holding buffer by 'h' cmd. The line in mode buffer will be deleted by
# cmd 'd'.
# then, excute the next sed cmd.
# when line contain '11011' be matched, the line will be replaced by the line
# we stored in the holding buffer before.
#NOTE: cmd 'G' just print the line which we save in holding buffer after the matched line.
sed -e '/DATE/ {h;d;}' -e '/11011/{G;}' t_file
sed script file
sed_script
#my firs sed script
/DATE/ {h;d;}
/11011/{G;}
How to execute the script:
#chmod +x sed_script
# sed -f sed_script t_file