Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python zip() behavior in bash?

Tags:

Is there similar Python zip() functionailty in bash? To be specific, I'm looking for the equivilent functionality in bash without using python:

$ 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
like image 496
daniel Avatar asked May 26 '11 21:05

daniel


People also ask

What is zip () in Python?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

What is $s in bash?

From man bash : -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.

Can you zip more than two lists Python?

The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments.


2 Answers

Pure bash:

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

(old answer) Look at 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

(assuming you've got the =() operator like in zsh, otherwise it's more complicated).

like image 154
liori Avatar answered Sep 18 '22 08:09

liori


code

[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
like image 26
Pavan Yalamanchili Avatar answered Sep 18 '22 08:09

Pavan Yalamanchili