Apenas em linhas com uma string específica, substitua outra string

-1

Script de shell para localizar as ocorrências da palavra "aqui" e somente nessas linhas, substitua a palavra "this" pela palavra "that". Descanse todas as outras linhas são impressas como estavam.

    
por Parul kusmatia 27.11.2017 / 16:55

2 respostas

6

Supondo que você tenha file.txt contendo essas duas linhas:

here is this
but not this

Você pode executar o seguinte comando sed para substituir "this" por "that" em todas as linhas que contêm a palavra "here", deixando todas as outras linhas intactas:

sed '/\bhere\b/ s/\bthis\b/that/g' file.txt

Observe que \b nos padrões simboliza limites de palavras, ou seja, o início ou o fim de uma palavra. Sem esses, e. "lá" também corresponderia.

Saída:

here is that
but not this

Leia man sed para mais informações.

    
por Byte Commander 27.11.2017 / 16:58
1

Uma solução awk (ou seja, GNU Awk no Ubuntu) poderia ser assim:

awk '{ if ( /\yhere\y/ ) gsub ( /\ythis\y/ , "that" ); print }'

\y em awk é igual a \b em sed , cuja importância aqui @ByteCommander já foi explicada . Compare este exemplo:

$ awk '{if(/here/)gsub(/\ythis\y/,"that");print}' <<EOL
> here is this
> here is athis
> there is this
> EOL
here is that
here is athis
there is that

$ awk '{if(/\yhere\y/)gsub(/\ythis\y/,"that");print}' <<EOL
> here is this
> here is athis
> there is this
> EOL
here is that
here is athis
there is this

Explicações

  • if ( conditional expression ) action - awk if declaração: se a linha atualmente processada contiver expressão condicional , faça ação
  • /\yhere\y/ - expressão regular que corresponde à palavra "aqui"
  • gsub(x,y) - g lobally (= várias vezes por linha, se necessário) sub stitute x por y
  • print - imprime a linha atualmente processada
por dessert 27.11.2017 / 20:55