The SED beauty

Sed is one of the unix beauties. Simple, standard, absolutely
text/driven, and overall, powerful as The Brain. Look at the examples.

Simple replace:

# sed -e 's/en_US/es_ES/g' /etc/sysconfig/i18n

Replace only on determined lines:

# sed -e '/disable/s/yes/no/' /etc/xinetd.d/pop3s

Adding after a line:

# sed -e '/ListenAddress ::/a\AllowUsers root' /etc/ssh/sshd_config

Deleting a line:

# sed -e '/only_from/d' /etc/xinetd.d/swat

Making a backup, just with "-i"

# sed -i.bak -e '/\/AutoPPP/s/\#//' /etc/mgetty+sendfax/login.config

Replace spaces on start lines:

# sed 's/^ *//' file

More than 2 spaces with one:

# sed 's/[ ]\{2,\}/ /g' file

This is my precious, my ring: Once we have to replace this text...

old: {pdf=FILE text=TEXT}
new: {pdf=FILE title=FILE text=TEXT}

... on *THOUSANDS* of "page.txt" files in a BIIIG directory tree! Of
course, "FILE" and "TEXT" were different on each. With a little help
from my friends Sed and Find, took just a minute:

# find . -name page.txt -print -exec \
> sed -i -e \
> "s/{pdf=\(.*\?\) text=\(.*\?\)}/{pdf=\1 title=\1 text=\2}/g" "{}" \;

Note: ".*" is a GREEDY expression (RT regex FM). To avoid GREEDINESS,
you should use ".*?"


No comments: