sed: examples of the magic command for GNU / Linux

sed command

In GNU / Linux there are many tools that are already pre-installed with the system and that not everyone uses. Some of them are certainly unknown, instead, they could do many things to facilitate our daily work. Today I present you to the command thirst, it is not a rare utility, in fact it is well known. But maybe you did not know everything that this can do flow editor (hence its name Stream EDitor). A powerful legacy Unix program.

sed can accept a file as input, it will read it and will modify line by line according to the order given. The result will be shown by the standard output, that is, by the screen in this case. Thus it allows to manipulate data flows to find, cut, insert or replace lines of text using regular expressions. Maybe some features remind you of other tools like ed or ex.

But for you to understand better, here are some good practical examples of using sed. I have left them commented so that you know what each one is for and group them all within the same box:

#Ver las líneas de un fichero de texto de la 15 a la 17
sed -n 15,17p nombre.txt

#Mostrar todo el contenido excepto las líneas 10 a 14
sed 10,14d nombre.txt

#Mostrar cada 3º línea comenzando desde la 2
sed -n '2,3p' nombre.txt

#Eliminar la línea 4
sed 4d nombre.txt

#Eliminar la última línea, sea cual sea
sed $ d nombre.txt

#Eliminar un rango de líneas
sed '20 -34d ' nombre.txt
#Eliminar solo las lineas mencionadas
sed '29 -34! d ' nombre.txt

#Agregar una línea en blanco tras cada línea de texto
sed G nombre.txt

#Localizar "hola" y sustituirlo por "hello"
sed 's / hola / hello /' nombre.txt

#Sustituir palabra de una línea concreta
sed '4 s / peligro / seguridad /' nombre.txt

#Sustituir una línea donde se encuentre la palabra "adios" por otra línea escrita
sed '/ adios / c "Esta será la nueva línea"' nombre.txt

I hope I have helped you with this sed minitutorial...


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: AB Internet Networks 2008 SL
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.