Displays the number of lines omitted by the head and tail of the bash together.

Asked 1 years ago, Updated 1 years ago, 361 views

When I use the head or tail commands to display some of the files, I wonder if I can display "how many lines were not displayed" together.

If file.txt is:

aaa
bbb
ccc
ddd
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

I would be happy if it was displayed like this

$head-n3file.txt

aaaa Corporation
bbb
ccc
(2 lines omitted)

Thank you for your cooperation.

bash

2022-11-04 00:10

3 Answers

How about using awk?

awk-vN=3'NR<=N{print}END {if(NR-N>0)printf("(%dlines omitted)\n",
NR-N)}'file.txt

Displays the NR<=N{print} content until the specified number of lines N is reached, and finally displays the number of lines remaining.


2022-11-04 00:10

$sed --version
sed (GNUsed) 4.8

$ cat file.txt | {sed-u'3q'; printf'(%d lines omitted)\n'$(wc-l);}
aaaa Corporation
bbb
ccc
(2 lines omitted)

$ seq 100 | {sed-u'3q'; printf'(%d lines omitted)\n'$(wc-l);}
1
2
3
(97 lines omitted)


2022-11-04 00:10

If you do something complicated, you can show it together as you have already answered, but if you do it separately, it will be easier.

The wc command displays the number of lines in the file.

$wc-l file.txt
5file.txt
$ wc-l<file.txt
5


2022-11-04 00:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.