1

I have a bunch of csv files in a directory, and I want to remove from each row the second comma. Example:

Input:

53,900,1001,-45.4247,9.87187,541.65
75,900,0102,37.0896,4.24087,558.35
75,900,1101,37.3096,4.25814,561.65
46,901,0003,-51.3833,-20.2645,578.35
3,901,0003,-57.302,-23.0063,578.35

Desired Output:

53,9001001,-45.4247,9.87187,541.65
75,9000102,37.0896,4.24087,558.35
75,9001101,37.3096,4.25814,561.65
46,9010003,-51.3833,-20.2645,578.35
3,9010003,-57.302,-23.0063,578.35

Is this possible with sed? Many thanks in advance!

3 Answers 3

10

This way :

sed 's/,//2' file.csv

This option is documented here as a flags avaible to the s command.

number

Only replace the numberth match of the regexp.

1
  • 1
    It is even a POSIX feature of sed Commented Apr 5, 2022 at 7:37
1
awk -F "," 'BEGIN{OFS=","}{$2=$2$3;$3="";gsub(/,,/,",",$0);print}' file.txt

output

53,9001001,-45.4247,9.87187,541.65
75,9000102,37.0896,4.24087,558.35
75,9001101,37.3096,4.25814,561.65
46,9010003,-51.3833,-20.2645,578.35
3,9010003,-57.302,-23.0063,578.35
3
  • Please don't overcomplicate things. The op asked for a sed solution which was provided. Commented Apr 4, 2022 at 18:45
  • 2
    @ValentinBajrami while I'm no fan of overcomplicating things, we have had a few discussions on Meta (one, two, three) indicating general support for answering using alternative tools. Commented Apr 4, 2022 at 20:09
  • gsub(/,,/,",",$0) would remove every non-contiguous pair of empty fields, not just the one you want. You have a habit of using gsub() when you should be using sub() in your answers. You also don't need the ,$0 arg as that's the default. Commented Apr 5, 2022 at 11:17
0

The gensub function from GNU awk cam also be used in this scenario:

$ gawk '{$0=gensub(/,/,"",2)}1' file
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.