replace nth occurence of string in each line of a text file

I have large text files with space delimited strings (2-5). The strings can contain "'" or "-". I'd like to replace say the second space with a pipe.

What's the best way to go?

Using sed I was thinking of this:

sed -r 's/(^[a-z'-]+ [a-z'-]+\b) /\1|/' filename.txt

Any other/better/simpler ideas?


You can add a number at the end of the substitute command. For example, the following will substitute the second occurrence of old with the string new on each line of file:

sed 's/old/new/2' file

So, instead of your proposed solution, you can use:

sed 's/ /|/2'

For more information, see e.g. this sed tutorial.


Did you try your version? Did it work? Because I think it is basically a good idea. I would do slightly differently, though:

sed -re 's/^([^ ]+ +[^ ]+) /\1|/'

This will accept any characters in a word that is not space, and will accept more than one spaces between the first two words.