1

Do you have any bash solution to remove N lines from stdout?

like a 'head' command, print all lines, only except last N

Simple solition on bash:

find ./test_dir/ | sed '$d' | sed '$d' | sed '$d' | ...

but i need to copy sed command N times

Any better solution? except awk, python etc...

Klaus
  • 538
  • 8
  • 26
Dmitry Dubovitsky
  • 2,186
  • 1
  • 16
  • 24

3 Answers3

7

Use head with a negative number. In my example it will print all lines but last 3:

head -n -3 infile
Birei
  • 35,723
  • 2
  • 77
  • 82
  • `$head -n -3 somefile.ext` throws error `head: illegal line count -- -3` on OSX / BSD General Commands Manual – gtzilla Oct 11 '18 at 03:53
2

if head -n -3 filename doesn't work on your system (like mine), you could also try the following approach (and maybe alias it or create a function in your .bashrc)

head -`echo "$(wc -l filename)" | awk '{ print $1 - 3; }'` filename

Where filename and 3 above are your file and number of lines respectively.

2

The tail command can skip from the end of a file on Mac OS / BSD. tail accepts +/- prefix, which facilitates expression below, which will show 3 lines from the start

tail -n +3 filename.ext

Or, to skip lines from the end of file, use - prefixed, instead.

tail -n -3 filenme.ext

Typically, the default for tail is the - prefix, thus counting from the end of the file. See a similar answer to a different question here: Print a file skipping first X lines in Bash

gtzilla
  • 1,265
  • 1
  • 16
  • 21