并排打印四行,然后重新开始

时间:2016-11-12 05:22:45

标签: bash loops while-loop

我有一个文件

6/28
Save As You Go Transfer Credit From Xxxxxxxxxxx3495
1.00
10.00
7/7
Save As You Go Transfer Credit From Xxxxxxxxxxx3495
1.00
11.00
7/8
Save As You Go Transfer Credit From Xxxxxxxxxxx3495
1.00
12.00
7/12
Save As You Go Transfer Credit From Xxxxxxxxxxx3495
1.00
13.00

我想像$line $line $line $line那样打印,然后每四行打印一次,然后开始换行。我认为循环是要走的路 - 但它不起作用

#!/bin/bash

while read line
do
for ((i=0; i<3 ; i++;))
do
echo $line | tr "\n" " "

done
i=0
done < /tmp/moo.txt

这就是我想要打印文件的方式:

6/28 Save As You Go Transfer Credit From Xxxxxxxxxxx3495 1.00 10.00
7/7 Save As You Go Transfer Credit From Xxxxxxxxxxx3495 1.00 11.00
7/8 Save As You Go Transfer Credit From Xxxxxxxxxxx3495 1.00 12.00
7/12 Save As You Go Transfer Credit From Xxxxxxxxxxx3495 1.00 13.00

2 个答案:

答案 0 :(得分:2)

由于N mod 4定期更改范围[0;3]1, 2, 3, 0, 1, 2, 3, 0, 1, ...,您可以测试模运算的结果是否为零,并打印换行符如果是:

i=0
while read line
do
  printf '%s ' "$line"
  (( ++i % 4 )) || printf '\n'
done < /tmp/moo.txt

在此示例中,printf打印带有附加空格(%s)的文件中的下一行。 %s格式规范代表一个字符串(第一个参数是格式字符串,下一个参数根据格式字符串传递)。

表达式(( ++i % 4 ))arithmetic expansion,它将i变量递增1,然后执行模4运算。请注意使用预增量运算符。

在算术上下文中,零被解释为布尔false。如果由于OR operator printf '\n'算术运算的结果为零,则执行||命令。一些清晰的例子:

(( 0 )) || echo zero
(( 1 )) && echo non-zero || echo zero 

输出

zero
non-zero

通过添加一些额外的逻辑很容易修复尾随空格(在换行符之前):

i=0
while read line
do
  (( ++i % 4 )) && d=' ' || d=$'\n'
  printf '%s%s' "$line" "$d"
done < /tmp/moo.txt

请注意使用ANSI C-quoting作为换行符:$'\n'

使用AWK相同

使用AWK实用程序可以实现相同的逻辑:

awk '{ printf "%s%s", $0, (NR % 4 ? " " : "\n") }' /tmp/moo.txt

我们使用了AWK's conditional expressionbuilt-in auto-set NR变量。

<强> P.S。

为什么printfThere are serious reasons使用printf代替echo

答案 1 :(得分:1)

尝试:

#!/bin/bash

while read line
do
for ((i=0; i<3 ; i++;))
do
echo -n `echo $line | tr "\n" " "`

done
i=0
done < /tmp/moo.txt