Skip to content
Advertisement

remove comma in jsonpath template using bash

I have a JSON path template query.

oc get event jsonpath='{range .items[*]},{@.name}{","}{@.message}{","}{@.evenname}'{"n"}{end}'> /tmp/test.csv

i’m redirecting it to csv.

name1,message of event one,eventname1
name2,message of,event,two,eventname2
name3,message of event three,eventname3
name4,message of, event four,eventname4

getting comma in a message from above output , i want to replace the comma with space for the second column(message) in the bash script.

Anyone has any thoughts on how can achieve this.

Expected result

name1,message of event one,eventname1
name2,message of event two,eventname2
name3,message of event three,eventname3
name4,message of event four,eventname4

Advertisement

Answer

Assuming you can change the field delimiter to a character known to not exist in the data (eg, |), you would now be generating:

name1|message of event one|eventname1
name2|message of,event,two|eventname2
name3|message of event three|eventname3
name4|message of, event four|eventname4

From here we can use sed to a) remove/replace , with <space> and then b) replace | with ,:

$ sed 's/[ ]*,[ ]*/,/g;s/,/ /g;s/|/,/g'

NOTE: the s/[ ]*,[ ]*/g is needed to address the additional requirement of stripping out repeating spaces (as would occur in line #4 if we replace , with <space>)

When applied to the data this generates:

name1,message of event one,eventname1
name2,message of event two,eventname2
name3,message of event three,eventname3
name4,message of event four,eventname4

Another option using awk (for OP’s current data using the , as the field delimiter):

awk -F',' '                              # input field delimiter = ","
{ x=$1","                                # start new string as field #1 + ","

  sep=""                                 # initial separator = "" for fields 2 to (NF-1)

  for (i=2;i<NF;i++) {                   # loop through fields 2 to (NF-1)
      gsub(/^[ ]+|[ ]+$/,"",$i)          # trim leading/trailing spaces
      x=x sep $i                         # append current field to x along with sep
      sep=" "                            # use " " as separator for rest of fields
  }

  printf "%s,%sn", x, $NF               # print "x" plus "," plus the last field (NF)
}'

When applied to the data this generates:

name1,message of event one,eventname1
name2,message of event two,eventname2
name3,message of event three,eventname3
name4,message of event four,eventname4
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement