Tuesday, June 26, 2012

Linux - Intro to sed - Text replacement

Linux - Inplace Text Replacement


Here's one way you can do a text replacement in Linux. This is useful for mass-editing files like html, source code, or whatever text file you use.

Example 1: Turn Lead into Gold

Here are the contents of a file, dwarvenVault

Hint: cat outputs a file to the terminal.
alchemist@BogWarfs:/opt/test$ cat dwarvenVault 
Inventory
-------------------
 5 x Lead bricks
10 x Lead bracelets
20 x Lead rings
42 x Lead swords
alchemist@BogWarfs:/opt/test$

Let's do alchemy!

alchemist@BogWarfs:/opt/test$ sed 's/Lead/Gold/g' dwarvenVault 
Inventory
-------------------
 5 x Gold bricks
10 x Gold bracelets
20 x Gold rings
42 x Gold swords
alchemist@BogWarfs:/opt/test$ cat dwarvenVault
Inventory
-------------------
 5 x Lead bricks
10 x Lead bracelets
20 x Lead rings
42 x Lead swords
alchemist@BogWarfs:/opt/test$ 

Aw poop, we have the change, but it didn't stick in the file. Ho hum.

Protip:Use -i to change it in place.
alchemist@BogWarfs:/opt/test$ sed -i 's/Lead/Gold/g' dwarvenVault 
alchemist@BogWarfs:/opt/test$ cat dwarvenVault 
Inventory
-------------------
 5 x Gold bricks
10 x Gold bracelets
20 x Gold rings
42 x Gold swords
alchemist@BogWarfs:/opt/test$ 

Example 2: Multiple files

You can also use a regex or some other mechanism to change many files at once.

alchemist@BogWarfs:/opt/test/$ ls
dwarvenVault  elvenVault  goblinVault
alchemist@BogWarfs:/opt/test/$ cat *
Inventory
-------------------
 5 x Lead bricks
10 x Lead bracelets
20 x Lead rings
42 x Lead swords
Inventory
--------------------
 24 x Lead bricks
300 x Lead bracelets
 50 x Lead rings
 15 x Lead swords
Inventory
--------------------
191 x Lead bricks
  3 x Lead bracelets
  1 x Lead rings
 26 x Lead swords
alchemist@BogWarfs:/opt/test/$ sed -i 's/Lead/Gold/g' *Vault
alchemist@BogWarfs:/opt/test/$ cat *
Inventory
-------------------
 5 x Gold bricks
10 x Gold bracelets
20 x Gold rings
42 x Gold swords
Inventory
--------------------
 24 x Gold bricks
300 x Gold bracelets
 50 x Gold rings
 15 x Gold swords
Inventory
--------------------
191 x Gold bricks
  3 x Gold bracelets
  1 x Gold rings
 26 x Gold swords
alchemist@BogWarfs:/opt/test/$ 

Yer a wizard 'Arry

No comments:

Post a Comment