-2

I have a large list of files exists inside a particular directory (with full path). I'm trying to delete files from this directory where the line count in the file is greater than 1 (2 or more).

How can it be done?

Diksha
  • 21

3 Answers3

2

You can use this. Before you execute it, you should first try with echo instead of rm.

for i in dir/*; do
  lines=$(wc -l "$i")
  if test $lines -gt 1; then
    rm "$i"
  fi
done
ilkkachu
  • 138,973
RalfFriedl
  • 8,981
1

Try this,

find . -type f -maxdepth 1 -exec bash -c '[[ $(wc -l < "$1") -gt 1 ]] && rm "$1"' _ '{}' \;
  • . -type f -maxdepth 1 to find files in the current directory
  • $(wc -l < "$1") -gt 1 check if the line count of is greater than 1
  • rm "$1"' _ ' remove files only in the current directory.
Siva
  • 9,077
  • Hmm, I can't see how this would be limited to files in the current directory? You'd need -maxdepth 1 or some -type d -prune style trick – ilkkachu Aug 15 '18 at 09:16
1

The awk solution:

wc -l /path/to/dir/* | head -n -1` | awk '$1>1 {print $2}' | xargs rm

Notes:

  • No support for special characters in that simple version
  • Remember that wc -l doesn't count lines but occurrences of linefeeds. So a file with two lines (but without a LF on the second one) will be reported has having "1" line.
xenoid
  • 8,888