Replace only first instance of a character
is for globally, that is to substitute all occurrences of
If you want to do only one substitution per line, take off the
And for completeness:
You can also specify which occurrence to substitute. For instance, to substitute only the second occurrence:
sed, you can also substitute all occurrences starting from the second one (in effect, all but the first one) with:
To perform two substitutions, in this case:
Where it gets more complicated is when the pattern can match the substitution (or parts of it), for instance when substituting
sed has no built-in mechanism to address that. You may want to use
perl instead in that case:
perl -pe '$i = 0; s/,/$i++ < 2 ? "<,>" : $&/ge'
perl -pe is
sed mode (note that the regex syntax is different). With the
e flag of the
s/// operator, the replacement is considered as code. There, we replace
<,> only when our incremented counter is < 2. Otherwise, we replace the
, with itself (
$& actually referring to the matched string like
You can generalise that for a range or set of substitutions. Like for 3rd to 5th and 7th to 9th:
perl -pe '$i = 0; s/,/$i++; $i >=3 && $i <= 5 || $i >= 7 && $i <= 9 ? "<,>" : $&/ge'
To replace only the first occurrence in the whole input (as opposed to in each line):
sed -e 's/,/;/;t done' -e b -e :done -e 'n;b done'
That is, upon the first successful substitution, go into a loop that just prints the rest of the input.
sed, you can use the pseudo address 0:
I suppose it's a typo, but the
command you wrote in your question is something completely different.
;. That is, applying the
g command (replace the pattern space with the content of the hold space (empty here as you never hold anything)) for sections of the file in between one that contains
s and the next one that contains
Pure bash solution
while IFS=\, read -r a b ; do echo "$a;$b" ; done <file.csv
Or just for fun
paste -d\; <(cut -d, -f1 file.csv) <(cut -d, -f1 --complement file.csv)