Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files containing exactly 16 lines?

Tags:

grep

bash

awk

I have to find files that containing exactly 16 lines in Bash.

My idea is:

find -type f | grep '/^...$/'

Does anyone know how to utilise find + grep or maybe find + awk?

Then,

  • Move the matching files another directory.
  • Deleting all non-matching files.
like image 245
user2493340 Avatar asked Jun 17 '13 12:06

user2493340


4 Answers

I would just do:

wc -l **/* 2>/dev/null | awk '$1=="16"'
like image 51
Benoit Avatar answered Sep 27 '22 19:09

Benoit


Keep it simple:

find . -type f |
while IFS= read -r file
do
    size=$(wc -l < "$file")
    if (( size == 16 ))
    then
        mv -- "$file" /wherever/you/like
    else
        rm -f -- "$file"
    fi
done

If your file names can contain newlines then google for the find and read options to handle that.

like image 34
Ed Morton Avatar answered Sep 27 '22 17:09

Ed Morton


You should use grep instead of wc because wc counts newline characters \n and will not count if the last line doesn't ends with a newline.

e.g.

grep -cH '' * 2>/dev/null | awk -F: '$2==16'

for more correct approach (without error messages, and without argument list too long error) you should combine it with the find and xargs commands, like

find . -type f -print0 | xargs -0 grep -cH '' | awk -F: '$2==16'

if you don't want count empty lines (so only lines what contains at least one character), you can replace the '' with the '.'. And instead of awk, you can use second grep, like:

find . -type f -print0 | xargs -0 grep -cH '.' | grep ':16$'

this will find all files what are contains 16 non-empty lines... and so on..

like image 32
cajwine Avatar answered Sep 27 '22 19:09

cajwine


GNU sed

sed -E '/^.{16}$/!d' file
like image 30
Endoro Avatar answered Sep 27 '22 18:09

Endoro