Search a character within a special field AWK

Viewed 68

I would need to parse a field in a awk script to search for a special character and if exists to be replaced with "," or "/"

the awk script transforms a CSV into DAT. the Field separator defined is ; but sometimes users send a comment that contains the field separator. in order to fix this we would need to parse the COMMENT field which is NUMBER $4 and in case the field contains ; to be replaced with / or comma

here it is the file

"PAT";"TARO";"GEO";"COMMENT"
"FRT";"1256";"USA";"THIS IS A COMMENT ; AFTER COMMENT"

outcome expected

PAT TARO    GEO COMMENT
FRT 1256    USA THIS IS A COMMENT / AFTER COMMENT


BEGIN { 
  FS = ";" ;
  OFS = "   " ;

print "pat taro geo comment";   


}

NR==1{
next
}

{
pat= $1;
taro = $2;
geo = $3 ; 
comment = $4 ;
}

if $4 contains ";" then 
replace with "/"
end if;

{
    print "pat,taro,geo,comment";   

}

how can I do this ?

Thank you in advance

1 Answers

If the fields don't have newlines in them, you could use for example GNU awk and its FPAT feature:

$ gawk '
BEGIN {
    FPAT="([^;]*)|(\"[^\"]+\")"
}
{
    print $4
}' file

Output:

"COMMENT"
"THIS IS A COMMENT ; AFTER COMMENT"

If you still want to replace the ; in the comment, add gsub(/;/,"/",$4) before the print.

Edit:

$ gawk '
BEGIN {
    FPAT="([^;]*)|(\"[^\"]+\")"   # FPAT;separates;semicolons;"and quotes"
    print "pat taro geo comment"  # print header
}
{
    for(i=1;i<=NF;i++)            # loop all 4 fields
        gsub(/^"|"$/,"",$i)       # remove quotes

    gsub(/;/,"/",$4)              # change the ; in $4 to /

    pat= $1                       # no need for this mut since you wanted
    taro = $2
    geo = $3
    comment = $4

    print pat,taro,geo,comment    # output new vars but you could as well:
    # print $1,$2,$3,$4           # use this too or
    # print $0                    # since record was rebuilt on gsub
}' file

Output:

pat taro geo comment
PAT TARO GEO COMMENT
FRT 1256 USA THIS IS A COMMENT / AFTER COMMENT
Related