Prasanna
Prasanna

Reputation: 23

Comma separated value within double quote

I have a data file separated by comma, data enclosed by "":

$ head file.txt
"HD","Sep 13 2016 1:05AM","0001"
"DT","273093045","192534"
 "DT","273097637","192534" ..

I want to get the 3rd column value (0001) to be assigned to my variable.

I tried

FILE_VER=`cat file.txt | awk -F',' '{if ($1 == "HD") print $3}'`

I don't get any value assigned to FILE_VER. Please help me with correct syntax.

Upvotes: 2

Views: 118

Answers (4)

hek2mgl
hek2mgl

Reputation: 157947

You were almost there. Simply removing the quotes should be good enough:

foo=$(awk -F, '$1=="\"HD\""{gsub(/"/,"",$3);print $3}' file)

Upvotes: 0

user3680055
user3680055

Reputation: 53

You can change the file to substitute the comma and quotes to tab:

tr -s '\"," "\t' < filename | awk '{print $3}'

Maybe there is a solution using only awk, but this works just fine!

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

not sure this is the most optimal way but works:

FILE_VER=$(awk -F',' '$1 == "\"HD\"" {gsub("\"","",$3); print $3}' file.txt)
  1. test for HD between quotes
  2. remove quotes before printing result

Upvotes: 0

sat
sat

Reputation: 14949

Another awk version:

awk -F'"' '$2 == "HD"{print $6}' file

Upvotes: 1

Related Questions