NickJeff
NickJeff

Reputation: 21

Replace every second comma with space using sed

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.

Upvotes: 2

Views: 604

Answers (3)

sseLtaH
sseLtaH

Reputation: 11247

Using sed

$ sed 's/\(.\{3\}\),/\1 /g' input_file
1,2 5,32 67,28 40,30...
2,4 90,18 22,40 20,15....

Upvotes: 1

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2915

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"," ")_'

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

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....

Upvotes: 1

Related Questions