Replace on Nth Occurrence

0

Eu tenho este código

sed '/Sometexts/ r newtext.txt' old.txt > new.txt

Isto substitui a String 'Sometexts' pelo conteúdo do arquivo de texto newtext.txt

mas eu quero substituir a segunda ocorrência da String 'Sometexts'

Como posso arquivá-lo?

    
por The KingMaker 12.11.2013 / 13:03

2 respostas

1

se a solução não estiver limitada a sed , então awk é seu amigo, com o seguinte oneliner:

awk 'BEGIN{file="NewText.txt";}{if(/SOMETEX/) count++; if(count==2){while((getline<file)>0) {print};count++;} else print;}' OldText.txt > new.txt

O que faz:

awk 'BEGIN{file="NewText.txt";} #sets the path to the 
                                file that will be inserted
{if(/SOMETEX/) count++; #counts occurences of SOMETEX (regex-matching)
 if(count==2) #if we just found the second occurence then
{while((getline<file)>0) {print};count++;}  #read all lines of 
                                             file and print them
else print; #otherwise just print the line
}' 
    
por 12.11.2013 / 18:13
1

Existem várias maneiras de fazer isso.

Provavelmente, o mais simples é transformar seu arquivo inicial em uma única (string muito longa) substituindo a nova linha por outro caractere (eu uso cap ^ porque é bastante inofensivo nesse contexto), procurando e substituindo a n-ésima ocorrência da string de pesquisa e, em seguida, colocando as novas linhas de volta em seu lugar.

Isso pode ser feito com um único comando:

 tr '\n' '^' < my_file | sed 's/Sometexts/ r newtext.txt/2' | tr '^' '\n' > new.txt

Você também pode fazer isso com awk ou em uma única linha com sed, mas rapidamente fica confuso.

Editar: se você está com medo de usar ^, você pode usar este comando único:

 sed ':a;N;$!ba;s/Sometexts/ r newtext.txt/2' file
    
por 12.11.2013 / 13:27