2011-05-26 48 views
11

在bash中是否有類似的Python zip()函數?具體而言,我在bash尋找equivilent功能,無需使用python:bash中的Python zip()行爲?

$ echo "A" > test_a 
$ echo "B" >> test_a 
$ echo "1" > test_b 
$ echo "2" >> test_b 
$ python -c "print '\n'.join([' '.join([a.strip(),b.strip()]) for a,b in zip(open('test_a'),open('test_b'))])" 
A 1 
B 2 
+0

只是出於好奇:你爲什麼要在這種情況下,避免了使用Python? – dusktreader 2011-05-26 21:58:20

+1

將其嵌入到PBS腳本中。想保持儘可能簡單,但不一定反對python – daniel 2011-05-27 13:30:20

回答

14

純慶典:

[email protected]:~$ zip34() { while read word3 <&3; do read word4 <&4 ; echo $word3 $word4 ; done } 
[email protected]:~$ zip34 3<a 4<b 
alpha one 
beta two 
gamma three 
delta four 
epsilon five 
[email protected]:~$ 

(舊回答)看join

liori:~% cat a 
alpha 
beta 
gamma 
delta 
epsilon 
liori:~% cat b 
one 
two 
three 
four 
five 
liori:~% join =(cat -n a) =(cat -n b) 
1 alpha one 
2 beta two 
3 gamma three 
4 delta four 
5 epsilon five 

(假設你有=() operator like in zsh,否則它會更復雜)。

+0

這真棒。我查看了加入前,但我是在印象之下,你需要像SQL加入 – daniel 2011-05-27 13:31:29

+0

共同的標識符在這種情況下,功能增加了一點靈活性。除了「壓縮」這些行外,我還需要在它們之間添加一些文本。謝謝! – daniel 2011-05-27 13:33:21

+0

你有什麼'=()'的鏈接嗎?這是不可能的谷歌:) – Marian 2014-06-26 15:33:45

4

代碼

[tmp]$ echo "A" > test_a 
[tmp]$ echo "B" >> test_a 
[tmp]$ echo "1" > test_b 
[tmp]$ echo "2" >> test_b 
[tmp]$ cat test_a 
A 
B 
[tmp]$ cat test_b 
1 
2 
[tmp]$ paste test_a test_b > test_c 
[tmp]$ cat test_c 
A 1 
B 2 
0

你能做到這一點與cat -n兩個步驟之後join。 (cat -n在每行的開始再現與行號文件join加入就行號兩個文件。)

$ echo "A" > test_a 
$ echo "B" >> test_a 
$ echo "X" > test_b 
$ echo "Y" >> test_b 
$ cat -n test_a > test_a.numbered 
$ cat -n test_b > test_b.numbered 
$ join -o 1.2 -o 2.2 test_a.numbered test_b.numbered 
A X 
B Y 
+0

ahhh ....這就是如何加入:) – daniel 2011-05-27 13:31:55