Text files
Get information
Count the lines in a file:
Awk:
awk 'END {print NR}' file.txtGrep:
grep -c '^' file.txtSed:
sed -n '$=' file.txtWc:
wc -l file.txt
Filter by line
Print the first line of a file:
Awk:
awk 'NR==1' file.txtHead:
head -n 1 file.txtSed:
sed 1q file.txtor:
sed -n 1p file.txt
Print the first 10 lines of a file:
Awk:
awk 'NR<=10' file.txtHead:
head -n 10 file.txtSed:
sed 10q file.txtor:
sed -n 1,10p file.txt
Print the 5th line of a file:
Awk:
awk 'NR==5' file.txtHead:
head -n 5 file.txt | tail -n 1Sed:
sed -n 5p file.txtor:
sed '5!d' file.txt
Print the last 10 lines of a file:
Sed:
sed -e :a -e '$q;N;11,$D;ba' file.txtTail:
tail -n 10 file.txt
Print the last line of a file:
Awk:
awk 'END{print}' file.txtSed
sed '$!d' file.txtor:
sed -n '$p' file.txtTail:
tail -n 1 file.txt
Print a range of lines:
Awk:
awk 'NR==8, NR==12' file.txtSed:
sed '8,12!d' file.txtor:
sed -n 8,12p file.txt
Filter by regular expression
Print lines that match a regular expression:
Awk:
awk '/^#/' file.txtGrep:
grep -E '^#' file.txt
Print lines that DO NOT match a regular expression:
Awk:
awk '!/^#|^$/' file.txtGrep:
grep -vE '^#|^$' file.txt
Print next line after line matching a regular expression:
Awk:
awk '/[Uu]nix/ {getline; print}' file.txtSed:
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
Links
- awk_sed.txt - Chart of similar operations with sed and awk
- awk - Print just the last line of a file? - Stack Overflow
- count lines in a file - Unix & Linux Stack Exchange
- How to print particular line number by using sed command
- sed, a stream editor
- shell - How to print 5 consecutive lines after a pattern in file using awk - Stack Overflow
- The GNU Awk User’s Guide
- Unix / Linux: Show First 10 or 20 Lines Of a File – nixCraft