Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Replace first six commas for each line in a text file

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 |.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!