0

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
3
  • 1
    show the test.json using regex to parse json is not recommended. Commented Aug 14, 2018 at 14:13
  • 1
    Please replace cat foo | grep "bar" with grep "bar" foo. cat is for concatenation, not for printing. Commented Aug 14, 2018 at 14:14
  • Please avoid "Give me the codez" questions. Instead show the script you are working on and state where the problem is. Also see How much research effort is expected of Stack Overflow users? Commented Aug 15, 2018 at 1:47

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Giving me below error new1.sh: line 19: syntax error near unexpected token (' new1.sh: line 19: paste <(echo "$var1") <(echo "$var2") <(echo "$var3")'
I'm specifically using bash syntax. Make sure your shebang line is #!/bin/bash and you are not invoking the script like sh myscript.sh but like bash myscript.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.