sed - extract data between 2 words from different parts of .txt by combining 3 sed commands

Viewed 85

I have multiple .txt with info like this:

"commercial_name":"THE OUTBACK","contact_name":"JEFF","contact_person":"MANAGER","working_place"

there is a lot of garbage behind and after the given sentence. I want to get results like this:

THE OUTBACK,JEFF,MANAGER

All in the same line for each .txt file, but jump line for the next .txt.

I am doing with 3 different sed commands

sed -n 's:.*"commercial_name"\(.*\)"contact_name".*:\1:p' *.txt

sed -n 's:.*"contact_name"\(.*\)"contact_person".*:\1:p' *.txt

sed -n 's:.*"contact_person"\(.*\)"working_place".*:\1:p' *.txt

even if I combine these 3, the result is:

:"THE OUTBACK",

-all commercial names 1 line for each .txt

:"JEFF",

-all contact names 1 line for each .txt

:"MANAGER",

-all contact person 1 line for each .txt

I want to extract all the info in the same line:

THE OUTBACK,JEFF,MANAGER

then the info for the next .txt in the next line and so on.

2 Answers

You may use this awk:

awk 'BEGIN {
    FS=OFS=","
}
{
   gsub(/"/, "")
   for(i=1; i<=NF; ++i) {
      if (split($i, entry, ":") == 2)
         map[entry[1]] = entry[2]
   }
   print map["commercial_name"], map["contact_name"], map["contact_person"]
}' file
THE OUTBACK,JEFF,MANAGER

With awk

  1. we set FS and OFS separately:
awk -v FS=',|:' -v OFS=',' '{print $2,$4,$6}'  file
"THE OUTBACK","JEFF","MANAGER"
  1. and gsub for removing double quotes:
awk -v FS=',|:' -v OFS=',' '{gsub(/"/, "")} {print $2,$4,$6}'  file
THE OUTBACK,JEFF,MANAGER

This code:

  • why printing $2,$4,$6?

Ed Morton gives a detail explication here: converting regex to sed or grep regex

  • Using Ed's code, you can see it with for

awk -v FS=',|:' -v OFS=',' '{gsub(/"/, "")} {for (i=1; i<=NF;i++) print "Record", NR, "Field", i, ":  " $i;}{print  RT}'  file
Record,1,Field,1,:  commercial_name
Record,1,Field,2,:  THE OUTBACK
Record,1,Field,3,:  contact_name
Record,1,Field,4,:  JEFF
Record,1,Field,5,:  contact_person
Record,1,Field,6,:  MANAGER
Record,1,Field,7,:  working_place
  • In this case, we are interested in fields 2, 4 and 6:

{print $2,$4,$6}

--

Related