我有来自标准输出的数据列(在我的例子中是对mysql的调用),我想在每个循环中附加文件中的列。我该怎么办?
Standard output:
a1
a2
....
an
保存在名为 table.dat 的文件中:
table.dat:
a1
a2
....
an
然后生成另一个输出:
Further standard output:
b1
b2
....
bn
追加到表.dat:
table.dat:
a1 b1
a2 b2
.... ....
an bn
。等等。我可以使用粘贴,但我需要三个步骤:
line producing standard output > tmpfile;
paste prevfile tmpfile > table
mv table prevfile;
有没有更快的方法,也许通过使用awk?
此解决方案:向文件添加新列生成一个空表。
您可以通过从 stdin读取以下内容来使用这样的粘贴:
paste <(command1) <(command2)
例如
paste <(cat f1) <(cat f2)
而不是:
paste f1 f2
只是为了澄清一些细节,在给出的两个流没有相同数量的元素的情况下。阿努巴瓦提出的paste
结果:
[ ~]$ cat t1.txt
a1
a2
a3
[ ~]$ cat t2.txt
b1
b2
[ ~]$ paste t1.txt t2.txt
a1 b1
a2 b2
a3
否则,与 Bash 只是为了好玩:
[ ~]$ cat test.sh
#!/bin/bash
f1=t1.txt
f2=t2.txt
getNumberOfRows(){
wc -l "$1"|cut -d" " -f1
}
s1=$(getNumberOfRows "$f1")
s2=$(getNumberOfRows "$f2")
[[ $s1 -le $s2 ]] && min="$s1" || min="$s2"
i=1
while read; do
echo "$REPLY $(sed -n ${i}p $f2)"
(( i++ ))
[[ $i -ge $min ]] && break
done < "$f1"
[ ~]$ ./test.sh
a1 b1
a2 b2
[ ~]$
在此示例中,您可以看到,如果文件大于另一个文件,则不会显示其他行。
当然,您可以通过paste
中的命令输出或使用此脚本更改文件;)
使用paste
:
paste <(COMMAND1) <(COMMAND2)
使用脚本 :请参阅此答案以了解如何在循环中读取命令输出。