Skip to content

Unix tools

Text files

Get information

  • Count the lines in a file:

    • Awk:

        awk 'END {print NR}' file.txt
    • Grep:

        grep -c '^' file.txt
    • Sed:

        sed -n '$=' file.txt
    • Wc:

        wc -l file.txt

Filter by line

  • Print the first line of a file:

    • Awk:

        awk 'NR==1' file.txt
    • Head:

        head -n 1 file.txt
    • Sed:

        sed 1q file.txt

      or:

        sed -n 1p file.txt
  • Print the first 10 lines of a file:

    • Awk:

        awk 'NR<=10' file.txt
    • Head:

        head -n 10 file.txt
    • Sed:

        sed 10q file.txt

      or:

        sed -n 1,10p file.txt
  • Print the 5th line of a file:

    • Awk:

        awk 'NR==5' file.txt
    • Head:

        head -n 5 file.txt | tail -n 1
    • Sed:

        sed -n 5p file.txt

      or:

        sed '5!d' file.txt
  • Print the last 10 lines of a file:

    • Sed:

        sed -e :a -e '$q;N;11,$D;ba' file.txt
    • Tail:

        tail -n 10 file.txt
  • Print the last line of a file:

    • Awk:

        awk 'END{print}' file.txt
    • Sed

        sed '$!d' file.txt

      or:

        sed -n '$p' file.txt
    • Tail:

        tail -n 1 file.txt
  • Print a range of lines:

    • Awk:

        awk 'NR==8, NR==12' file.txt
    • Sed:

        sed '8,12!d' file.txt

      or:

        sed -n 8,12p file.txt

Filter by regular expression

  • Print lines that match a regular expression:

    • Awk:

        awk '/^#/' file.txt
    • Grep:

        grep -E '^#' file.txt
  • Print lines that DO NOT match a regular expression:

    • Awk:

        awk '!/^#|^$/' file.txt
    • Grep:

        grep -vE '^#|^$' file.txt
  • Print next line after line matching a regular expression:

    • Awk:

        awk '/[Uu]nix/ {getline; print}' file.txt
    • Sed:

        sed -n '/[Uu]nix/ {n;p;}' file.txt
  • Print next 7 lines after line matching a regular expression:

    • Awk:

        awk -v l=7 '/[Uu]nix/ {for(i=l; i; --i) {getline; print}}' file.txt