Shell-如何为每行添加增量空白

时间:2018-10-18 20:34:56

标签: shell unix

if [ $(grep -c 'Health Status: RED' $LOG) -gt 0 ]; then
    $(grep 'Server:' $LOG > $TMP )
    while read -r line
    do
        echo "$instance,1,$line"
    done < "$TMP"

    else
    echo "\n$instance,0,Health Status: GREEN\n"
fi

以上代码的输出如下:

Instance1,1,Server: EMEA

Instance1,1,Server: NAM

Instance1,1,Server: ASIA

Instance1,1,Server: AUSTRALIA

我需要在每行$instance变量中添加增量空间,在$instance之后添加一个空间,如下所示。请注意,行数不是固定的。

Instance1 ,1,Server: EMEA  ==> One blank space added after Instance1

Instance1  ,1,Server: NAM ==> two blank spaces added after Instance1

Instance1   ,1,Server: ASIA ==> three blank spaces added after Instance1

Instance1    ,1,Server: AUSTRALIA ==> four blank spaces added after Instance1

任何输入将不胜感激。

2 个答案:

答案 0 :(得分:0)

尝试使用如下所示的printf

for ((i=3;i<10;i++)); do
   printf "%*s\n" $i ",1,"
done

答案 1 :(得分:0)

为此替换您的while

spaces_counter=1
while read -r line
do
    echo "$instance$(printf "%0.s " $(seq 1 $spaces_counter)),1,$line"
    (( spaces_counter += 1 ))
done < "$TMP"

一些解释:

  • $(seq 1 $spaces_counter):输出1到$spaces_counter的整数
  • $(printf "%0.s " $(seq 1 $spaces_counter)):使用上方的seq打印一定数量的空格。
  • “%0.s”之后的字符是您要重复的字符。

这是基于以下答案:Print a character repeatedly in bash

结合您的代码。