bash连接多个文件,并且空替换(-e选项) [英] bash join multiple files with empty replacement (-e option)
问题描述
我有以下代码将多个文件连接在一起.它工作正常,但我想将空值替换为0,所以我使用了-e"0".但这是行不通的. 有什么想法吗?
I have following code to join multiple files together. It works fine but I want to replace the empty values to 0, so I used -e "0". But it doesn't work. Any ideas?
for k in `ls file?`
do
if [ -a final.results ]
then
join -a1 -a2 -e "0" final.results $k > tmp.res
mv tmp.res final.results
else
cp $k final.results
fi
done
示例:
file1:
a 1
b 2
file2:
a 1
c 2
file3:
b 1
d 2
Results:
a 1 0 1 0
b 2 1 0
c 2
d 2
expected:
a 1 1 0
b 2 0 1
c 0 2 0
d 0 0 2
推荐答案
它的文献资料很少,但是当使用join
时,-e
选项只能与-o
选项一起使用.每次循环时都需要修改订单字符串.以下代码将生成所需的输出.
It's poorly documented, but when using join
the -e
option only works in conjunction with the -o
option. The order string needs to be amended each time around the loop. The following code should generate your desired output.
i=3
orderl='0,1.2'
orderr=',2.2'
for k in $(ls file?)
do
if [ -a final.results ]
then
join -a1 -a2 -e "0" -o "$orderl$orderr" final.results $k > tmp.res
orderl="$orderl,1.$i"
i=$((i+1))
mv tmp.res final.results
else
cp $k final.results
fi
done
如您所见,它开始变得凌乱.如果您需要进一步扩展此功能,则可能值得使用功能更强大的工具,例如awk或python.
As you can see, it starts to become messy. If you need to extend this much further it might be worth deferring to a beefier tool such as awk or python.
这篇关于bash连接多个文件,并且空替换(-e选项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!