Linux File Processing: head and tail examples
Last updated:Table of Contents
- Output first N lines
- Output last N lines
- Output lines starting at line N
- Output first N lines, skip first line
Output first N lines
Use head -n N
Example: output first 2 lines
$ head -n 2 file.txt
1) line 1
2) line 2
Output last N lines
Example: output last 4 lines of file
$ tail -n 4 multiline-file.txt
3) line 3
4) line 4
5) line 5
6) line 6
Output lines starting at line N
Use tail -n +N
Example: output lines starting at line 3
source file has 6 lines
1) line 1 2) line 2 3) line 3 4) line 4 5) line 5 6) line 6
Use
tail -n +3
to output lines string at line 3:$ tail -n +3 file.txt 3) line 3 4) line 4 5) line 5 6) line 6
Output first N lines, skip first line
Can be done with a combination of head and tail.
Example: print first 3 lines of csv file, without the header
The source file looks like this:
"name","age","home_state" "alice",14,"AK" "bob",20,"DC" "charlie",49,"CA" "david",13,"CA" "eugene",33,"NY"
Run
tail -n +2 file.csv | head -n 3
:$ tail -n +2 file.csv | head -n 3 "alice",14,"AK" "bob",20,"DC" "charlie",49,"CA"