Replace Text in Variables & Single/Multiple-Files in UNIX

      

text-replace-shell-scriptShell Script is fun. I love it when I know which commands to use. There are almost thousands of

Here is a simple trick to Replace Text and Variables in Files in UNIX. We will use command sed – it is very useful to find and replace text in single or multiple files.

Replace Text in Single File

Replacing hello with hello_world in a single file.

sed -i 's/hello/hello_world/g' somefile.txt

Check the arguments

  • -i = edit the file “in-place” – sed will directly modify the file if it finds anything to replace
  • s = substitute the following text
  • hello = what you want to substitute
  • hello_world = what you want to replace
  • g = global, match all occurrences in the line

Replace Text in Multiple Files

Following command will replace hello with hello_world in multiple files in one go.

sed -i 's/hello/hello_world/g'  *.txt

Replace Value of Variable

I had a requirement in shell script to replace value of a variable and use it somewhere. For example: Say variable $path has value “root/user/home” and I need to replace “/” with “-” so that the value looks like “root-user-home”.

${variable//search/replace}
  • variable – Is name of the variable you want to replace value.
  • search – String in variable you want to replace.
  • replace – String you want to replace with.

Facebook  Twitter      Stumbleupon  Delicious
  

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.