1

I have a file of a table, the columns of which were separated by spaces. I wrote the following bash script to convert the spaces to commas:

#!/bin/bash for f in /home/foo/*; do i=`basename $f` i2=${i%.*} cut -f 1,2,3,4 < $f | tr -s [:blank:] ',' > $i2.csv done 

But I missed something that my datetime has a space between the date and time, and now there is a comma there. The datetime's comma is the third one, is there any way to replace the third comma for all the rows with a space in linux?

3
  • 1
    sed 's/,/ /3' maybe? I'm not sure what your input file really looks like. Commented Oct 20, 2017 at 14:32
  • @BenjaminW. It looks like this: 6000,0,2012-01-01,08:00:00,9,foo,x,0.123 next rows would be the same just different data Commented Oct 20, 2017 at 14:43
  • @BenjaminW. Your solution worked perfectly, if you want to post it as a solution, i an accept it as the correct answer. Thanks! :) Commented Oct 20, 2017 at 14:59

2 Answers 2

1

The sed s command has a flag to specify which occurrence of a regex to apply the command to:

sed 's/,/ /3' infile 

modifies the third , in each line and replaces it with a space.

Sign up to request clarification or add additional context in comments.

1 Comment

@αғsнιη Quote from POSIX spec: "n: Substitute for the nth occurrence only of the BRE found within the pattern space" So any sed for which this solution doesn't work is not POSIX conformant. I see it in the man pages for BSD sed and macOS sed.
0

To work in all sed implementation you could use:

sed -r 's/^(([^,]*,){2}[^,]*),/\1 /' infile 

1 Comment

The flag to replace a specific occurrence is specified by POSIX.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.