Prepending a header file
# sed script to put header.txt above first line
# run with sed -i -f <this_script> <filename(s)>
1{h; r header.txt
D; }
2{x; G; }
changes only pieces inside a section
see
http://www.student.northpark.edu/pemente/sed/sedfaq3.html#s3.3
Say for a section like this...
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/ gpgcheck=1
enabled=0
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-centos4
This will change
enabled=0 to
enabled=1 only for this section, overwrite the old file and save a backup:
sed --in-place=_old '/\[centosplus\]/,/^\[/s/enabled=0/enabled=1/' the_file
Grouping-like stuff in substitution
Say you want to change
home to
home_sweet_home...use the
() to select the group, then
\1 to substitute it back in
echo "dummy:x:505:509::/home/dummy:/bin/bash" | sed 's/\/home\/\(.*\):/\/home_sweet_home\/\1:/g'
Search and replace in a file
sed 's/zork/Pork/gi' zorkstuff.txt | less
Like, throw out the
.wav extension on a bunch of files
ls *.wav |sed 's!\.wav$!!'
Replace every occurrence (the
g specifier) of 'Zork' with 'Pork' ignoring case (
i specifier)
Print first 5 lines
sed '5q' file
Print until you find 'blah', then stop
sed '/blah/q' file
Print line 52 of file
sed '52q;d' file
strip out lines that have a match in them
sed -n '/delete lines with me in them/!p' file
See also
--
MattWalsh - 21 Oct 2003
Topic revision: r7 - 16 Sep 2009 - 18:33:02 -
MattWalsh