Search code examples
linuxbashshellstring-formatting

Shell script that filters command output and saves it in Json formated list


never worked with shell scripts before,but i need to in my current task.
So i have to run a command that returns output like this:

    awd54a7w6ds54awd47awd refs/heads/SomeInfo1  
    awdafawe23413f13a3r3r refs/heads/SomeInfo2 
    a8wd5a8w5da78d6asawd7 refs/heads/SomeInfo3 
    g9reh9wrg69egs7ef987e refs/heads/SomeInfo4 

And i need to loop over every line of output get only the "SomeInfo" part and write it to a file in a format like this:

    ["SomeInfo1","SomeInfo2","SomeInfo3"]

I've tried things like this:

    for i in $(some command); do
      echo $i | cut -f2 -d"heads/" >> text.txt
    done

But i don't know how to format it into an array without using a temporary file.
Sorry if the question is dumb and probably too easy and im sure i can figure it out on my own,but i just don't have the time for it because its just an extra conveniance feature that i personally want to implement.


Solution

  • Using Perl one-liner

    $ cat petar.txt
        awd54a7w6ds54awd47awd refs/heads/SomeInfo1
        awdafawe23413f13a3r3r refs/heads/SomeInfo2
        a8wd5a8w5da78d6asawd7 refs/heads/SomeInfo3
        g9reh9wrg69egs7ef987e refs/heads/SomeInfo4
    
    $ perl -ne ' { /.*\/(.*)/ and push(@res,"\"$1\"") } END { print "[".join(",",@res)."]\n" }' petar.txt
    ["SomeInfo1","SomeInfo2","SomeInfo3","SomeInfo4"]