Save multiple variables from bash script to text file

时间:2015-10-29 15:56:48

标签: bash

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.

3 个答案:

答案 0 :(得分:2)

您可以在每次迭代时创建文件。在done之后移动I / O重定向。使用:

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

这避免了变量;如果您需要它,可以使用原始代码的固定版本(始终使用$lines,而不是使用$num_lines一次)。请注意,问题中的代码具有此版本避免的UUoC(无用的cat)。

答案 1 :(得分:1)

您可以使用

来避免循环
wc -l *Daily.txt | awk '{ print $1 -1 }' > /destdrive/linesTally2014.txt

或(当你想少1时)

  parameters:

        int n @prompt("enter number") = default(2);

    connections:

        for i=0..n do { // here the n gives me a syntax error (unexpected NAME, expected { 
            //do things

        }   

答案 2 :(得分:0)

上述建议可能更好,但您使用 脚本时遇到的问题是您使用>进行重定向,这会覆盖文件。使用>>,它将附加到文件中。

echo $lines >> /destdrive/linesTally2014.txt