Home > Net >  Replace every second comma with space using sed
Replace every second comma with space using sed

Time:03-30

I am looking to replace every second comma on every line of a text file with a space using sed or awk in the Linux terminal. The file looks like:

1,2,5,32,67,28,40,30...
2,4,90,18,22,40,20,15....

and I want a specific software input file format:

1,2 5,32 67,28 40,30
2,4 90,18 22,40 20,15...

I tried

sed -r 's/([^,]   [^,])  /\1\s/g' Test.txt > Test2.txt

but this did not work. Any help would be much appreciated.

CodePudding user response:

You can use

sed -E 's/(,[^,]*),/\1 /g' file > newfile

Details:

  • (,[^,]*), matches and captures into Group 1 a comma and then any zero or more chars other than a comma, and then matches a comma
  • \1 replaces the match with Group 1 value and adds a space right after.

The -E option enables POSIX ERE regex syntax.

See the online demo:

#!/bin/bash
s='1,2,5,32,67,28,40,30...
2,4,90,18,22,40,20,15....'
sed -E 's/(,[^,]*),/\1 /g' <<< "$s"

Output:

1,2 5,32 67,28 40,30...
2,4 90,18 22,40 20,15....

CodePudding user response:

slighly verbose awk-based solution that's confirmed working on gawk, mawk-1, mawk-1.996, and nawk :

[g/m/n]awk 'sub("^"(_="[^,] ,")_,"&"(_="\3\21"))sub(","_," ")_'

I picked \032\021 as a safer choice than merely going with subsep, since the chance of this combo appearing is rather low. A more concise solution would be like

 mawk 'sub("^"(_="[^,] ,")_,"&\5")sub(",\5"," ")_'
  • Related