17

for example i have this file :

cat myfile
1
2
3
4
5

i want to print all lines except first 2 line . output should be like this :

tail -n $(( $(wc -l myfile | awk '{print $1}') - 2 )) myfile
3
4
5

Yes , out put is correct. but there is a problem , we have 5 line in this sample file right ? if i use more that 5 in this command output should be empty but it is not !!!

tail -n $(( $(wc -l myfile | awk '{print $1}') - NUMBER )) myfile

this outout should be empty but it is not

tail -n $(( $(wc -l myfile | awk '{print $1}') - 8 )) myfile

1
2
3
4
5

myfile can contain X lines... Thanks for help

network
  • 281
  • 1
  • 2
  • 4

2 Answers2

34

tail -n+3 outputs all lines starting from the third one.

head -n-3 outputs all lines except for the last three.

ctrueden
  • 103
  • 4
choroba
  • 18,638
  • 4
  • 48
  • 52
  • line number are variable and i dont know how many line there are . want to keep all except last 3 lines – network Apr 29 '16 at 23:51
  • 1
    That's not what you described in the question, but `head -n-3` should give you what you need. – choroba Apr 29 '16 at 23:53
  • i have edit question. but this file is output of a script and we dont know how many line have ... – network Apr 29 '16 at 23:58
  • You don't need to know the number of lines. – choroba Apr 29 '16 at 23:59
  • 1
    tried is it not what i need for example if i want have all line except 8 lines but i have 5 line only .so output should be empty :tail -n-8 myfile 1 2 3 4 5 – network Apr 30 '16 at 00:07
  • @behnam: Use `+` with `tail`, not `-`, as I did. – choroba Apr 30 '16 at 00:18
  • slightly tangential comment: i just came across a util that is similar to `tail` called Debian `buthead`, which more people should have the chance to enjoy: https://manpages.debian.org/jessie/buthead/buthead.1.en.html (it outputs all "but head"... as in "all but N lines from the head") – pestophagous Jul 27 '20 at 21:03
2

I know this is old, but for posterity.

given the input (as posted by OP),

cat << EOF > myfile
1
2
3
4
5
EOF

you can solve the problem using awk

awk 'FNR > 2 {print $1}' myfile

will yield desired result

3
4
5

tested with awk version (GNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2))

bgs
  • 21
  • 2