mahendra rathod
mahendra rathod

Reputation: 1638

grep multiple string from text file and export it to CSV

i have shell script which is producing multiple output

for example

#/bin/bash
var1=`cat test.json | grep "test" | awk -F ' ' '{print $1}'`
var2=`cat test.json | grep -e "new" | awk -F ':' '{print$5}'`
var3=`cat test.json | grep -e "new-test" | awk -F ':' '{print$8}'`

echo $var1,var2,var3

output of the first var1 is

1 
2 
3 
4 
5

output of the first var2 is

3
4
5
6
7

output of the first var3 is

834
45
345
73
23

how do I create a csv file with the following format?

1,3,834
2,4,45
3,5,345
4,6,73
5,7,23

Upvotes: 0

Views: 1459

Answers (1)

glenn jackman
glenn jackman

Reputation: 246877

The paste command is what you want, together with bash process substitutions:

paste -d, <(echo "$var1") <(echo "$var2") <(echo "$var3")
1,3,834
2,4,45
3,5,345
4,6,73
5,7,23

Make sure you quote the variables to maintain the newlines therein.


Your pipelines can be simpler: cat is unneeded, and awk can do what grep does:

paste -d, \
    <(awk -F ' ' '/test/     {print $1}' test.json) \
    <(awk -F ':' '/new/      {print $5}' test.json) \
    <(awk -F ':' '/new-test/ {print $8}' test.json)

Upvotes: 5

Related Questions