Given a text file a.txt
, how to cut the head or tail from the file?
For example, remove the first 10 lines or the last 10 lines.
to list all but the last 10 lines of a file:
head -n -10 file
to list all but the first 10 lines of a file:
tail -n +10 file
To omit lines at the beginning of a file, you can just use tail
. For example, given a file a.txt
:
$ cat > a.txt
one
two
three
four
five
^D
...you can start at the third line, omitting the first two, by passing a number prepended with +
for the -n
argument:
$ tail -n +3 a.txt
three
four
five
(Or just tail +3 a.txt
for short.)
To omit lines at the end of the file you can do the same with head
, but only if you have the GNU coreutils version (the BSD version that ships with Mac OS X, for example, won't work). To omit the last two lines of the file, pass a negative number for the -n
argument:
$ head -n -2 a.txt
one
two
three
If the GNU version of head
isn't available on your system (and you're unable to install it) you'll have to resort to other methods, like those given by @ruifeng.
to cut the the first 10 lines, you can use any one of these
awk 'NR>10' file
sed '1,10d' file
sed -n '11,$p' file
To cut the last 10 lines, you can use
tac file | sed '1,10d' | tac
or use head
head -n -10 file
cat a.txt | sed '1,10d' | sed -n -e :a -e '1, 10!{P;N;D;};N;ba'
IFS=$'\n';array=( $(cat file) )
for((i=0;i<=${#array[@]}-10;i++)) ; do echo "${array[i]}"; done