Comandos Avançados do sed e Correspondência de Padrões
Agora que dominamos a substituição básica e a edição in-place com sed, vamos explorar alguns recursos mais avançados:
- Usando delimitadores diferentes
- Usando intervalos de endereços para direcionar linhas específicas
- Combinando múltiplos comandos
Usando Delimitadores Diferentes
Embora tenhamos usado a barra / como delimitador em nossos comandos de substituição, o sed nos permite usar qualquer caractere como delimitador. Isso é especialmente útil quando o padrão ou o texto de substituição contém barras.
Vamos criar um arquivo com caminhos de arquivos:
echo "/usr/local/bin is in the PATH" > ~/project/paths.txt
echo "My config is in /etc/myapp/config.json" >> ~/project/paths.txt
Se quisermos substituir /usr/local/bin por /opt/bin, usar barras seria confuso:
sed 's/\/usr\/local\/bin/\/opt\/bin/' ~/project/paths.txt
Em vez disso, podemos usar um delimitador diferente, como #:
sed 's#/usr/local/bin#/opt/bin#' ~/project/paths.txt
Isso é muito mais legível! A saída deve ser:
/opt/bin is in the PATH
My config is in /etc/myapp/config.json
Outros delimitadores comuns incluem |, :, e _.
Endereçamento - Direcionando Linhas Específicas
O sed nos permite especificar em quais linhas aplicar a substituição. Isso é feito prefixando o comando com um endereço.
Vamos criar um novo arquivo com linhas numeradas:
echo "Line 1: This is the first line." > ~/project/numbered.txt
echo "Line 2: This is the second line." >> ~/project/numbered.txt
echo "Line 3: This is the third line." >> ~/project/numbered.txt
echo "Line 4: This is the fourth line." >> ~/project/numbered.txt
echo "Line 5: This is the fifth line." >> ~/project/numbered.txt
Para substituir "line" por "row" apenas na linha 3:
sed '3 s/line/row/' ~/project/numbered.txt
A saída deve ser:
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
Também podemos especificar um intervalo de linhas. Para substituir "line" por "row" nas linhas 2 a 4:
sed '2,4 s/line/row/' ~/project/numbered.txt
A saída deve ser:
Line 1: This is the first line.
Line 2: This is the second row.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
Outro recurso útil é a capacidade de corresponder linhas com base em um padrão. Por exemplo, para substituir "line" por "row" apenas nas linhas que contêm "third" ou "fourth":
sed '/\(third\|fourth\)/ s/line/row/' ~/project/numbered.txt
A saída deve ser:
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
Combinando Múltiplos Comandos
Podemos combinar múltiplos comandos sed usando a opção -e ou separando os comandos com ponto e vírgula.
Vamos substituir "first" por "1st", "second" por "2nd" e "third" por "3rd" em um único comando:
sed -e 's/first/1st/' -e 's/second/2nd/' -e 's/third/3rd/' ~/project/numbered.txt
Alternativamente, podemos usar ponto e vírgula:
sed 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
Ambos os comandos devem produzir a mesma saída:
Line 1: This is the 1st line.
Line 2: This is the 2nd line.
Line 3: This is the 3rd line.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
Vamos agora tornar essas alterações permanentes:
sed -i 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
E verificar as alterações:
cat ~/project/numbered.txt
Você deve ver o texto atualizado com números ordinais.