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
Code language: Arduino (arduino)
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
Code language: Arduino (arduino)

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}
Code language: Arduino (arduino)
  • 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.
Get our Articles via Email. Enter your email address.

You may also like...

5 Comments

  1. lattimore says:

    ${variable//search/replace}

    • rupkumar says:

      i want to replace abc as //abc
      it means i want to comment the word in whole file
      can u give me any suggestions please

  2. sagar mahajan says:

    Hi Viral …
    i have huge text file where in i want locate and delete whole record. What is the unix command fo r the same .

  3. rupkumar says:

    want to replace abc as //abc
    it means i want to comment the word in whole file

  4. Veena says:

    Hi Viral,
    I have a variable in java class name setNumVal it is initially 0.
    I would like to change this value with 1234 using script file

Leave a Reply

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