Command line tricks: manipulate texts


Command line tools: sed, awk.

Results will be printed instead of being saved to the original file (add -i if needed)


Print text

  • print the 1st and 3rd line of the file
    sed -n '1,3p' file # using sed
    cat file | awk '{ print $1 $3 }' # using awk
  • print the lines that contain "text"
    sed -n '/text/p' file.txt
  • print the last line and its line number
    sed -n '$p;$=' file # using sed
    awk 'END{print NR; print }' file # using awk
  • print even lines
    sed -n 'n;p' file
  • print odd lines
    sed -n 'p;n' file
  • print the first column with separator -
    awk -F- '{print $1}' file
  • print the 4th and the last columns
    awk '{ print $4, $NF}' file

Replace text

  • replace all the "test" with "test2", starting at the line N
    sed 's/test/test2/Ng' file
  • Find all the words, replace them with [word]
    sed -n 's/\w\+/[&]/gp'

Insert text

  • insert 'new line' before all the lines that start with 'test'
    sed '/^test/i\new line` file
  • insert 'new line' after all the lines that start with 'test'
    sed '/^test/a\new line` file
  • insert a prefix string to the begining of each line
    sed -e 's/^/prefix/' file > newfile
  • insert a prefix string to the end of each line
    sed -e 's/$/prefix/' file > newfile
  • insert "text" before the 10th line
    sed '10 i\text' input.txt

Delete text

  • delete all the lines from the 2nd line to the last line
    sed '2,$d' file
  • delete lines 2-5 and line 10
    sed -e '2,5d;10d' file

Back to Memo