Monday, February 19, 2007

Delete or Filter Lines in a File

SysAds are frequently filtering lines in a file. The stream editor command, sed, is a great tool for accomplishing this task. In our /etc/host file, it has blank lines and most of its entries have comments. We want to omit them from view. Here's a way of filtering them.

Display the filtered output to the screen
# sed -e '/^#/d' -e '/^$/d' /etc/hosts | more

Write the filtered output to a file
# sed -e '/^#/d' -e '/^$/d' /etc/hosts > /tmp/hosts.filtered

Just blank lines
# sed -e '/^$/d' /etc/hosts > /tmp/hosts.filtered

No comments: