ocra88
ocra88

Reputation: 123

remove quotes from specific field - integer between quotes

I want to remove quotes from specific field where there is an integer between quotes.

From this line : "AAA","99"

to this line : "AAA",99

Upvotes: 2

Views: 103

Answers (3)

Wintermute
Wintermute

Reputation: 44023

With awk:

awk -F , 'BEGIN { OFS = FS } $2 ~ /^"[0-9]+"$/ { gsub(/"/, "", $2) } 1'

That works as follows:

BEGIN { OFS = FS }  # Delimit output the same way as the input

$2 ~ /^"[0-9]+"$/ { # if the second field ($2) consists of only numbers encased
                    # by double quotes (i.e., matches the regex ^"[0-9]"$)
  gsub(/"/, "", $2) # remove the quotes from it
}
1                   # print in any case

To make this work for any (and not just a specific field), do the replacement in a loop:

awk -F , 'BEGIN { OFS = FS } { for(i = 1; i <= NF; ++i) if($i ~ /^"[0-9]+"$/) { gsub(/"/, "", $i) } } 1'

The changed bit here is

{                              # Do this unconditionally in every line:
  for(i = 1; i <= NF; ++i) {   # wade through all the fields
    if($i ~ /^"[0-9]+"$/) {    # then do with them the same thing as before.
      gsub(/"/, "", $i)
    }
  }
}

Upvotes: 1

anubhava
anubhava

Reputation: 784958

Using sed:

s='"AAA","99"'
sed 's/"\([0-9]*\)"/\1/g' <<< "$s"
"AAA",99

Upvotes: 3

Cyrus
Cyrus

Reputation: 88573

Try this with GNU sed:

echo '"AAA","99"' | sed -E 's/"([0-9]+)"$/\1/'

Output:

"AAA",99

Upvotes: 2

Related Questions