Cute ‘sed’ Tricks to Modify Specific Lines Within File

Here’s a cute trick to change or insert a line in a file given a line number using sed. You can pair it with grep to make it even more powerful with pattern matching.


if [ $# -lt 1 ]; then
   echo "Usage: $0 <filename>"

# Variables

# First, change line number $linenum, then insert
# two spaces at the beginning of that same line
sed -i "${linenum}c This line was changed" $file
sed -i "${linenum}s/^/   /" $file

# Insert a line at $linenum, then insert text at 
# the end of that same line.
sed -i "${linenum}i This line was inserted" $file
sed -i "${linenum}s/$/ end of line/" $file

# Match a particular pattern in the file and insert a line
# directly above the first match (will need massaging for
# multiple lines, perhaps using an array)
linenum=`grep -n pattern $file | head -n1 | cut -d: -f1`
linenum_above=`echo "$linenum - 1" | bc`
sed -i "${linenum_above}i This line was inserted" $file

echo "Resulting File:"
cat $file

As usual, take a look at the man pages for sed for more information.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:

There's 4 Comments So Far

Share your thoughts, leave a comment!