简体   繁体   中英

Unix - extract files with certain number of lines

(as an example), I have 10 files, named as such; file_name1.txt, file_name2.txt, file_name3.txt etc.

Each file has between 1-10 lines in it.

I want a command that will only print the files with a certain number of lines. ie I want to say print the file names if that file has 1 line , and then print the file names with 2 lines etc.

So I know to count the number of lines in the file it's wc -l filename , what's the next part, to say if wc -l filename == 1, print filename ?

I would use

wc -l * | awk '$1 == 10 {print $2}'

The awk invocation simply prints column 2 of every line where column 1 contains the value 10.

export wanted_lines=10
for i in file*; do [[ `wc -l $i | nawk '{print $1}'` == $wanted_lines ]] && cat $i; done

Update

export wanted_lines=10

declare wanted_lines as a variable, initialize to 10, and mark for automatic export to the environment of subsequently executed commands

for i in file*; do

This uses file globbbing to construct a list of every file in the current directory with a name that begins with "file". Each iteration the i variable will refer to the next value in the list

[[ expression ]]

square braces - Evaluate the expression and return a 0 or 1

`command`

backticks - executes command and replaces with output of command

wc -l $i

count the lines of variable i, in this case a file name

| nawk '{print $1}'

stdout of previous command is fed to stdin of nawk, printing the first column, in this case a file name

== $wanted_lines

Equality test, will return true or false (0 or 1) respectively

&& expression

control operator will run expression if and only if the previous expression returns true

In English: For every file beginning with the name "file", count the lines. If and only if the number of lines equals variable $wanted_lines, print the file.

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