0

My Input is:

Name, Country, City
Jason, US, Memphis, "1,000"
David, US, Little Rock, "8,765,453"
"Karam, Sage", US, Nazareth, "4,678"
"David, simon", US, Chicago, "1,234"

I want output as:

Name, Country, City
Jason, US, Memphis, "1000"
David, US, Little Rock, "8765453"
"Karam, Sage", US, Nazareth, "4678"
"David, simon", US, Chicago, "1234"

I want the comma to be removed from only 4th column and not first column.

1
  • My Input is: Name, Country, City, Amt Jason, US, Memphis, "1,000" David, US, Little Rock, "8,765,453" "Karam, Sage", US, Nazareth, "4,678" "David, simon", US, Chicago, "1,234" I want out put as: Name, Country, City, Amt Jason, US, Memphis, "1000" David, US, Little Rock, "8765453" "Karam, Sage", US, Nazareth, "4678" "David, simon", US, Chicago, "1234" I want the comma to be removed from only 4th column and not first column.
    – shashank
    Sep 14, 2017 at 4:30

4 Answers 4

0

Or with perl:

perl -pe 's/(\d),(\d)/$1$2/g' infile.txt

which just removes all commas that are surrounded by digits (\d).

I assumed that removing thousand separators was the essence in your task - not in which column the commas are located.

0
0

Assuming the 4th filed is your last filed, then an AWK approach would be.

awk -F\" '{gsub(",","",$(NF-1))}1' OFS=\" infile.txt

The output is:

Name, Country, City
Jason, US, Memphis, "1000"
David, US, Little Rock, "8765453"
"Karam, Sage", US, Nazareth, "4678"
"David, simon", US, Chicago, "1234"
2
  • How can we modify the command if there are n no of fields and we should delete the comma from the any field (having only numbers) which has comma.
    – shashank
    Sep 18, 2017 at 0:01
  • Name, Country, City, amount, comment Jason, US, Memphis, "1,000", "ABC,DEF" David, US, Little Rock, "8,765,453", "DEF,GHI" "Karam, Sage", US, Nazareth, "4,678", "GHI, JKL" "David, simon", US, Chicago, "1,234", "JKL, MNO"
    – shashank
    Sep 18, 2017 at 0:01
0

With sed:

sed -e ':a' -e 's/,\([^"]*"$\)/\1/;ta' infile.txt

You loop as long as there is a comma to be removed after the next-to-last double quote.

0

I recommend you use a CSV parser for CSV data: ruby has one

ruby -rcsv -e '
  data = CSV.read(ARGV.shift, :col_sep => ", ")
  out = CSV.new($stdout, :col_sep => ", ")
  data.each {|row| row[-1].delete! ","; out << row}
' file.csv
Name, Country, City
Jason, US, Memphis, 1000
David, US, "Little Rock", 8765453
"Karam, Sage", US, Nazareth, 4678
"David, simon", US, Chicago, 1234
1
  • last field quotes "..." should not be removed as OP expected output Sep 14, 2017 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.