2

I am running a bash script where I am appending the line count of the arguments, which are files, to another file. It does it correctly, but I keep getting a line that says "total X", X being the sum of all the line counts added together. How do I add an argument to only append the total if the # of arguments is above some number, X? This is what I currently have:

wc -l $@ >> $1
  • count=$(tail -1 $1) ; if [ $count -gt X ] ; then .... ; fi – Drav Sloan Jan 20 '15 at 19:31
2

I don't think you can suppress the total in the multi-argument form.

The simplest way I can think of is to stick to the one-argument form, when needed:

if [ "$#" -lt 5 ]
then
    for f in "$@"; do wc -l -- "$f"; done >>"$1"
else
    wc -l "$@" >> "$1"
fi
1

Strip off the last line from the wc output if there are too few lines for you to want a grand total.

word_counts=$(wc -l -- "$@")
newline='
'
if [ "$#" -le 9 ]; then
  word_count=${word_count%"$newline"*}
fi
printf '%s\n' "$word_count" >>"$1"

Note the double quotes in "$@" and around other variable substitutions, without this your script would break on file names containing whitespace (and some other special characters) with absolutely no redeeming benefit. Note also -- in wc -l -- "$@", in case a file name starts with a - (without --, wc would interpret that file name as an option).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.