Bash — find a list of files with more than 3 lines

我们两清 提交于 2021-02-04 13:17:05

问题


I have a directory of files and I want to find a list of files who has more than 2 lines.

I know I can use wc -l to test each file, but how do I wrap it up in bash?

Sorry for the newbie question, new to bash.


回答1:


You can use this find command:

find . -type f -exec bash -c '[[ $(wc -l < "$1") -gt 2 ]] && echo "$1"' _ '{}' \;



回答2:


Using xargs and awk:

$ find . -type f | xargs wc -l | awk '$1 > 2'

If you are in a git repositiory and want to count only tracked files, you can use following command:

$ git ls-files | xargs wc -l | awk '$1 > 2'



回答3:


Change to the directory, where the files are and use the following command:

for i in $(ls);
do
    if [ `grep -c '' $i` -gt 2 ]; then 
        echo `wc -l $i`;
    fi;
done

This works, of course, also as one-line-statement ;)

This line iterates over each file and use grep on it to get the pure line count. wc -l gets the count, too, but the result includes the filename ... I don't know, if you could use the value for comparison, too ... but it does not matter: If the line amount is greater 2 (-gt 2), then wc -l $i will output the line count and the file name. If you only want to see the file name, then substitute wc -l $i with $i.

Of course, i did not check, if each entry is a file. You could do that before checking the line count.

UPDATE: Although using ls for parsing is not recommended, one can still use it. You just have to check in advance that your filenames don't contain newline (or other odd) signs.



来源:https://stackoverflow.com/questions/33370890/bash-find-a-list-of-files-with-more-than-3-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!