FG

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

Fresh3 days ago
Mar 15, 202649744 views
Confidence Score0%
0%

Problem

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: Any other/better/simpler ideas?

Error Output

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

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Fix for: replace nth occurence of string in each line of a text file

Low Risk

You can add a number at the end of the substitute command. For example, the following will substitute the second occurrence of with the string on each line of : So, instead of your proposed solution, you can use: For more information, see e.g. this …

Awaiting Verification

Be the first to verify this fix

Sign in to verify this fix

Environment