-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
  • 2
    More detail would be useful: What OS, which shell you use, one file or several? –  Aug 15 '18 at 08:10
  • 1
    Sorry I am struggling to understand your question. Can you amend question to explain: What you mean by “with full path”? and “where the line count in the file is greater than 1”? (is this the number of line of the filename? if so is it just one line but wrapping, or is it more than one line? – ctrl-alt-delor Aug 15 '18 at 09:48
  • I do not understand the question at all, voting to close. – Vlastimil Burián Aug 15 '18 at 11:26
  • Interestingly enough, I almost never have difficulties understanding these sort of questions, claimed by the powers-to-be. This question is perfectly clear. – ajeh Aug 15 '18 at 21:31
  • 1
    Possible duplicate of [List (or move) only files with a certain number of lines?](https://unix.stackexchange.com/questions/245566/list-or-move-only-files-with-a-certain-number-of-lines) – Wildcard Aug 15 '18 at 23:31

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
  • 133,243
  • 15
  • 236
  • 397
RalfFriedl
  • 8,816
  • 6
  • 23
  • 34
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,017
  • 8
  • 56
  • 86
  • 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,648
  • 1
  • 24
  • 47