1

I have a simple bash script I have written to count the number of lines in a collection of text files, and I store each number of lines as a variable using a for loop. I would like to print each variable to the same text file, so that I may access all the line counts at once, from the same file.

My code is:

for f in *Daily.txt; do
    lines=$(cat $f | wc -l);
    lines=$(($num_lines -1));
    echo $lines > /destdrive/linesTally2014.txt;
done

When I run this, the only output I receive is of the final file, not all the other files.

If anyone could help me with this I would really appreciate it. I am new to bash scripting, so please excuse this novice question.

4
  • Is lines=$(cat ...) a typo for num_lines=$(cat ...)? Commented Oct 29, 2015 at 16:06
  • lines=$(( $(wc -l < "$f") - 1)) would be the proper way to get that value in one line. Commented Oct 29, 2015 at 16:07
  • @chepner: I think it is more a question that lines=$(($num_lines - 1)) is a typo for lines=$(($lines - 1)). But there is a problem with name consistency. Commented Oct 29, 2015 at 16:09
  • Thank you very much, this was really helpful. Commented Oct 29, 2015 at 17:16

3 Answers 3

2

You create the file on each iteration. Move the I/O redirection after the done. Use:

for f in *Daily.txt
do
    echo $(( $(wc -l < $f) - 1))
done > /destdrive/linesTally2014.txt

This avoids the variable; if you have a need for it, you can use a fixed version of the original code (use $lines throughout, instead of using $num_lines once). Note that the code in the question has a UUoC (Useless Use of cat) that this version avoids.

Sign up to request clarification or add additional context in comments.

Comments

1

You can avoid the loop with

wc -l *Daily.txt | awk '{ print $1 }' > /destdrive/linesTally2014.txt

or (when you want 1 less)

wc -l *Daily.txt | awk '{ print $1 -1 }' > /destdrive/linesTally2014.txt

Comments

0

The above suggestions are probably better, but the problem you're having with your script is your use of the > for redirection, which overwrites the file. Use >> and it will append to the file.

echo $lines >> /destdrive/linesTally2014.txt

1 Comment

No problem and welcome to SO; if you found any of the answers useful, upvote them, and mark the most helpful one as "accepted" by clicking the checkmark.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.