Shell 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.
${variable//search/replace}
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
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 .
want to replace abc as //abc
it means i want to comment the word in whole file
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