sed Commands

sed one liners

Insert character at beginning of line

Comment all nfs entries in fstab

sed -i '/nfs/s/^/#/' /etc/fstab

Uncomment all nfs entries in fstab

sed -i '/nfs/s/^#//g' /etc/fstab

Substitute a character at a specific line

Change line 108 of /etc/sudoers by removing the comment and immediate space that follows from wheel group

sed -i -e '108s/# //g' /etc/sudoers

Insert a string at a specific line number

sed -i '14iparser = future' /etc/puppetlabs/puppet/puppet.conf

copy a file / sub string in original

perl -i.orig2 -p -e 's/10.49.5.61/10.49.5.62/g' /etc/fstab

sed -n '1,609'p /var/log/tspulsemail.log > index.html

Substitute line feed with a space

awk

awk '{ print $1 }' | tr '\n' ' ' < file

perl

perl -p -e 's/\n/ /' file

Interpolating env vars vs. EOL

To use BOTH Unix $environment_vars and sed /end-of-line$/ pattern matching

Excerpt taken from: sed.sourceforge.net

The most readable is to enclose the script in “double quotes” so the shell can see the $variables, and to prefix the sed metacharacter ($) with a backslash:

sed "s/$user\$/root/" file

the shell interpolates $user and sed interprets \$ as the symbol for end-of-line.

Another method is to concatenate the script with ‘single quotes’ where the $ should not be interpolated and “double quotes” where variable interpolation should occur:

sed "s/$user"'$/root/' file

Share