0

How can I remove , after the first column of every line

$ cat tmp.txt
Name, Charles, James, Criss 
Age, 21, 25, 23

There may be n number of columns in the file.

And I need the output like

$ cat tmp.txt
Name, Charles James Criss
Age, 21 25 23

the , should not be deleted from first column.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
vadhan
  • 35
  • 3
  • I changed the title to something that it is more likely to be searched for. Any hints how to improve it? It still sounds a bit strange to me. – fedorqui Nov 27 '14 at 12:39

5 Answers5

6

You can tell sed to do it globally from the 2nd match:

$ sed 's/,//g2' file
Name, Charles James Criss 
Age, 21 25 23
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2
sed ':still
s/;//2
t still' tmp.txt

For non GNU sed where /g2 only change occurance n° 2

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
1

In Perl, i would do like the below through PCRE verb (*SKIP)(*F).

$ perl -pe 's/^\S+(*SKIP)(*F)|,//g' file
Name, Charles James Criss 
Age, 21 25 23

^\S+ matches one or more non-space characters which are present at the start of a line. (*SKIP)(*F) causes the match to fail. So now it matches all the commas except the one at the first column.

$ perl -pe 's/^[^,]*,(*SKIP)(*F)|,//g' file
Name, Charles James Criss 
Age, 21 25 23

^[^,]*, Match upto the first , then (*SKIP)(*F) make the match to fail, | from the remaining substring , match all the commas.

Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

With awk:

'BEGIN{FS=","}{for(i=1;i<NF+1;i++){if(i==1){printf $i", "}else{printf $i" "}};printf "\n"}'

Not the most elegant way to do it, but works nicely. The key here is setting the field separator to the character you wanted to remove anyway "," and then using printf (the formatting print function of awk) to add the "," back in between your field of interest (in this case if(i==1), adds the comma back in after only field 1.

Hobbes
  • 61
  • 4
0
awk '{gsub(/,/,"")}{$1=$1","}1' file
Name, Charles James Chriss
Age, 21 25 23

Remove every comma and put it back in first column.

Claes Wikner
  • 1,457
  • 1
  • 9
  • 8