Reputation: 21
I want to replace the first six ,
for each line in a text file using sed or something similar in linux.
There are more than six ,
on each line, but only the first six should be replaced by |
.
Upvotes: 1
Views: 122
Reputation: 58371
This might work for you (GNU sed):
sed 'y/,/\n/;s/\n/,/7g;y/\n/|/' file
Translate all ,
's to \n
's, then replace from the seventh \n
to the end of line by ,
's, then replace the remaining \n
's by |
's.
Upvotes: 1
Reputation: 14949
You can try this sed
,
sed -r ':loop; s/^([^,]*),/\1|/g; /^([^|]*\|){6}/t; b loop' file
(OR)
sed ':loop; s/^\([^,]*\),/\1|/g; /^\([^|]*|\)\{6\}/t; b loop' file
Test:
$ cat file
a,b,c,d,e,f,g,h,i,j,k
$ sed -r ':loop; s/^([^,]*),/\1|/g; /^([^|]*\|){6}/t; b loop' file
a|b|c|d|e|f|g,h,i,j,k
Note: This will work only if you do not have any pipe(|
) before that.
Upvotes: 0
Reputation: 52112
Sed doesn't really support the notion of "the first n occurrences", only "the n-th occurrence"; GNU sed has one for "replace all matches from the n-th on", which is not what you want in this case. To get the first six commas replaced, you have to call the s
command six times:
sed 's/,/|/;s/,/|/;s/,/|/;s/,/|/;s/,/|/;s/,/|/' infile
If, however, you know that there are no |
in the file and you have GNU sed, you can do this:
sed 's/,/|/g;s/|/,/7g' infile
This replaces all commas with pipes, then turns the pipes from the 7th on back to commas.
If you do have pipes beforehand, you can turn them into something that you know isn't in the string first:
sed 's/|/~~/g;s/,/|/g;s/|/,/7g;s/~~/|/g' infile
This makes all |
into ~~
first, then all ,
into |
, then the |
from the 7th on back into ,
, and finally the ~~
back into |
.
Testing on this input file:
,,,,,,X,,,,,,
,,,|,,,|,,,|,,,|
the first and third command result in
||||||X,,,,,,
||||||||,,,|,,,|
The second one would fail on the second line because there are already pipe characters.
Upvotes: 1
Reputation: 2457
Use the following pattern in sed: sed 's/old/new/<number>'
Where <number>
is the number of times you want this pattern applied.
You can replace <number>
with g
to apply the pattern to all occurrences.
Upvotes: 0