Comandos avanzados de sed y coincidencia de patrones
Ahora que hemos dominado la sustitución básica y la edición directa con sed
, exploremos algunas características más avanzadas:
- Usar diferentes delimitadores
- Usar rangos de direcciones para apuntar a líneas específicas
- Combinar múltiples comandos
Usar diferentes delimitadores
Si bien hemos estado usando la barra inclinada /
como delimitador en nuestros comandos de sustitución, sed
nos permite usar cualquier carácter como delimitador. Esto es especialmente útil cuando el patrón o el texto de reemplazo contiene barras inclinadas.
Creemos un archivo con rutas de archivos:
echo "/usr/local/bin is in the PATH" > ~/project/paths.txt
echo "My config is in /etc/myapp/config.json" >> ~/project/paths.txt
Si queremos reemplazar /usr/local/bin
con /opt/bin
, usar barras inclinadas sería confuso:
sed 's/\/usr\/local\/bin/\/opt\/bin/' ~/project/paths.txt
En cambio, podemos usar un delimitador diferente, como #
:
sed 's#/usr/local/bin#/opt/bin#' ~/project/paths.txt
¡Esto es mucho más legible! La salida debería ser:
/opt/bin is in the PATH
My config is in /etc/myapp/config.json
Otros delimitadores comunes incluyen |
, :
y _
.
Direccionamiento - Apuntar a líneas específicas
sed
nos permite especificar a qué líneas aplicar la sustitución. Esto se hace prefijando el comando con una dirección.
Creemos un nuevo archivo con líneas 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 reemplazar "line" con "row" solo en la línea 3:
sed '3 s/line/row/' ~/project/numbered.txt
La salida debería 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.
También podemos especificar un rango de líneas. Para reemplazar "line" con "row" en las líneas 2 a 4:
sed '2,4 s/line/row/' ~/project/numbered.txt
La salida debería 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.
Otra característica útil es la capacidad de coincidir con líneas basadas en un patrón. Por ejemplo, para reemplazar "line" con "row" solo en las líneas que contengan "third" o "fourth":
sed '/\(third\|fourth\)/ s/line/row/' ~/project/numbered.txt
La salida debería 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.
Combinar múltiples comandos
Podemos combinar múltiples comandos sed
usando la opción -e
o separando los comandos con punto y coma.
Reemplacemos "first" con "1st", "second" con "2nd" y "third" con "3rd" en un solo comando:
sed -e 's/first/1st/' -e 's/second/2nd/' -e 's/third/3rd/' ~/project/numbered.txt
Alternativamente, podemos usar punto y coma:
sed 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
Ambos comandos deberían producir la misma salida:
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.
Ahora hagamos estos cambios permanentes:
sed -i 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
Y verifiquemos los cambios:
cat ~/project/numbered.txt
Deberías ver el texto actualizado con números ordinales.