Fork me on GitHub


Bash snippet to remove a line from a file

May 5, 2011 | Computers

A while back I was working on a project that involved spooling up and shutting down a lot of Amazon EC2 instances while testing and I was constantly running in to an issue where my ~/.ssh/known_hosts file was out of sync with the server that I was connecting to.

Despite how simple it is, I could never remember the sed command to remove a line from a file. To help get around having to repeatedly manage my known_hosts file and/or look up the sed command I wrote a little function to remove lines from files using sed. Hopefully someone else out there finds this useful.

  1.  rmline() {
  2.   if ! [ "$#" = "2" ]; then
  3.   echo 'Invalid paramter count';
  4.   echo 'Usage: rmline line-num filename'
  5.   return;
  6.   fi
  8.   sed -i 0 "$1d" $2
  9.  }

So, stick that in your .profile and smoke it enjoy!