-1

Why am I getting this error:

line 9: [: too many arguments

when executing this bash script:

IN_FOLDER=period_to_import

cd $IN_FOLDER


for filename in *; do
WC=$(wc -w $filename)

if [ $WC -gt 33 ]
then
        rm $filename
fi
done
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Pedro
  • 81
  • 2
  • 8
  • `wc -w X` will output two arguments: `size filename`. You need to trim off the filename piece before doing the comparison. – Matt Clark May 07 '18 at 22:47
  • 2
    That can be avoiding by redirecting the file to `wc`, e.g. `$(wc -w <"$filename")` (and always remember to **quote** all variables within `[ .. ]` or with the equivalent `test ...`) – David C. Rankin May 07 '18 at 22:52
  • Yup. `[ "$WC" -gt 33 ]`, with the quotes, would have provided a more useful error message. – Charles Duffy May 07 '18 at 22:54
  • BTW, using lowercase names for all variables you define yourself is good form -- as variables that have meaning to the shell or POSIX-defined tools are required to be all-caps [by the POSIX specification](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html), using lower-case names for your own variables prevents conflicts. – Charles Duffy May 07 '18 at 22:56

1 Answers1

0

wc -w filename returns more than just the number of words. You can solve it like this:

if [ "${WC% *}" -gt 33 ]
then
        rm $filename
fi

${WC% *} trims everything to the right from the last space.

Although it is generally a bad idea to use unquoted variables in single brackets.

You may consider using awk instead:

IN_FOLDER=period_to_import

cd "$IN_FOLDER"

for filename in *; do
    if awk -v n=0 '{n++} END{if (n > 33) exit 0; else exit 1}' "$filename"
    then
        rm "$filename"
    fi
done

Just remember that globbing with * might not work in an empty directory.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
  • BTW, re: last-line aside, `shopt -s nullglob` will make `*` result to a zero-length list in an empty directory. (One needs to be aware of the side effects, though -- since `foo '*.txt'` will generally result in a file-not-found error whereas `foo` without any arguments may default to using stdin/stdout, `nullglob` can make situations one *intends* to be caught as an error result in unwanted behavior instead). – Charles Duffy May 07 '18 at 22:59