Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda