在bash中格式化增量变量输出

时间:2016-02-08 17:19:55

标签: bash while-loop

我遇到了一个相当简单的问题,一个变量的增量被打印成文件的连续字符串。

以下是代码示例:

#!/usr/bin/bash

_SesT=`date +%Y\/%m\/%d\ %H\-%M\-%S` 

n="0"

Execution_IT(){

    while read $3
    do
        ((n++))
        printf $n 
    done < ExecLog.txt

}

echo "test" && echo $_SesT
printf "Execution $(Execution_IT) Started $_SesT\r\n" >> ExecLog.txt

问题是输出的格式如下:

Execution  Started 2016/02/08 19-06-44
Execution 1 Started 2016/02/08 19-06-44
Execution 12 Started 2016/02/08 19-06-44
Execution 123 Started 2016/02/08 19-06-45
Execution 1234 Started 2016/02/08 19-06-45
Execution 12345 Started 2016/02/08 19-06-45
Execution 123456 Started 2016/02/08 19-06-46...

...而不是:

Execution 1 Started 2016/02/08 19-06-44
Execution 2 Started 2016/02/08 19-06-44
Execution 3 Started 2016/02/08 19-06-45...

这是我尝试cut -d后最常用的版本; awk; sed;甚至是类似C语法的for循环。有一个与while read line非常类似的版本,但输出完全相同。任何建议都将受到好评。

2 个答案:

答案 0 :(得分:2)

您的printf需要换行符:

printf "%d\n" "$n"

或者,

echo "$((++n))"

答案 1 :(得分:1)

据我了解,您只是将一行行打印到文件“ExecLog.txt”,具体而言,附加了最后一行。

该行包含的是文件中的行数和日期 这可以做得更好:

_logfile="ExecLog.txt"

n="$(wc -l <"$_logfile")"      ### count the number of lines in the log file.

_SesT="$(date +%Y\/%m\/%d\ %H\-%M\-%S)"   ### get time just before it is used.

echo "test $_SesT $_logfile"
printf "Execution %s Started %s\r\n" "$n" "$_SesT" | tee -a "$_logfile"

如果每行必须有一个循环来执行其他操作,请理解变量n在退出函数时不会丢失其值。因此,它可以在以后的脚本中使用。

将其打印在要添加到日志文件的行中:

#!/usr/bin/bash

_logfile="ExecLog.txt"

Execution_IT(){
    n="0"
    while IFS= read -r line
    do
        echo "loop $n"
        ((n++))
        # do something with $line.
    done < "$_logfile"
}

Execution_IT                              ### execute the loop.
_SesT="$(date +%Y\/%m\/%d\ %H\-%M\-%S)"   ### get time just before it is used.

echo "test time=$_SesT and count=$n"
printf "Execution %s Started %s\r\n" "$n" "$_SesT" >> "$_logfile"

了解这只是一个简单的例子,对比赛条件没有任何控制。其他一些脚本可能会在日志文件中写入一行,该脚本已经计算了行,并且在添加附加行之前。在这种情况下,计数将是错误的。或者运行此脚本的多个副本可能具有相同(不正确)的计数。

相关问题