Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace in shell scripting

Is it possible to search in a file using shell and then replace a value? When I install a service I would like to be able to search out a variable in a config file and then replace/insert my own settings in that value.

like image 348
Amanada Smith Avatar asked Jun 01 '12 20:06

Amanada Smith


People also ask

How do I find and replace in bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

What is $() called in bash?

$() is a command substitution It turns out, $() is called a command substitution. The command in between $() or backticks (“) is run and the output replaces $() .

What is $() in shell script?

$(command) or `command` Bash performs the expansion by executing command and replacing the com- mand substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

What is replace command in Linux?

replace looks for all occurrences of string from and replaces it with string to. You can specify one or more pairs of strings to search/replace in a single replace command. Use the -- option to indicate where the string-replacement list ends and the file names begin.


2 Answers

You can use sed to perform search/replace. I usually do this from a bash shell script, and move the original file containing values to be substituted to a new name, and run sed writing the output to my original file name like this:

#!/bin/bash
mv myfile.txt myfile.txt.in

sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt.

If you don't specify an output, the replacement will go to stdout.

like image 147
octopusgrabbus Avatar answered Sep 28 '22 07:09

octopusgrabbus


Sure, you can do this using sed or awk. sed example:

sed -i 's/Andrew/James/g' /home/oleksandr/names.txt
like image 22
Oleksandr Kravchuk Avatar answered Sep 28 '22 09:09

Oleksandr Kravchuk