简体   繁体   中英

remove n lines from STDOUT on bash

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...

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

head -n -3 infile

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM