简体   繁体   中英

Combining head and tail and outputting the file

I searched, but nothing I have found is working. I have a file.txt, I want to extract the top 50 lines and the last 50 lines, and output them into a new file. I tried:

head -n50 && tail -n50 > newfile.txt

But that only gives me the head file.

Any help>

Make a command group :

{ head -n50 file.txt && tail -n50 file.txt; } > newfile.txt

Or redirect once then again to append to the same file:

head -n50 file.txt > newfile.txt && tail -n50 file.txt >> newfile.txt

You don't want to read the data twice. A typical solution would be to implement a ring buffer in awk, but that's a bit of a pain. Reading once is tough with head, since it may consume all of the data and leave none for tail, so you cant just run head followed by tail. But you can take advantage of read's feature of not reading more than one line at a time and do:

{ for i in $(seq 50); do read line; printf "%s\n" "$line"; done; tail -50; } < file.txt > newfile.txt

This will avoid duplicating overlapping lines (eg, if you have only 30 lines of input, you won't get 60 lines of output).

You could also do this in gawk without a ring buffer by counting the lines and comparing the counts to the number of records:

gawk 'BEGINFILE {lineCount=0; while ((getline line < FILENAME) > 0 ) {lineCount++}} (FNR <= 50 || FNR >= lineCount-50 ) {print}' input_file.txt > output_file.txt

Technically, you're still reading the same file twice, but it's at least happening inside a single program.

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