Find and replace basics
This is a guide for useful find and replace commands. It is a bare-bones attempt at documenting my frequently used commands.
Search for a string
To find a string in a directory, use the following command.
grep -rl "string" /path/to/directory
grep
: is a command-line utility for searching plain-text data sets for lines that match a regular expression. -r
: (or --recursive
) option is used to traverse also all sub-directories of /path
.-l
: (or --files-with-matches
) option is used to only print filenames of matching files./path/
: path to the files you want to search through.
Example
The following searches for the string, “Resource” in the /build/docs/
directory.
grep -rl "Resource" /build/docs/
Use cases
This grep command is useful if you’ve received a pull request or issue mentioning an instance of a misspelled word, typo, or other unique string. The issue makes mention of one instance, but you want to check your user guide to see if that word exits else where. Rather than opening every file in your directory, you can search and have grep print out the existing files.
Find and replace
To find and replace a string, use the following command.
sed -i 's/Your_String/Your_Replacement_String/g' your-file.xml
-i
: By default, sed
writes its output to the standard output. This option tells sed
to edit files in place. If an extension is supplied, a backup of the original file is created.s
: The substitute command, probably the most used command in sed./
: Delimiter character. Your_String
: Normal string or a regular expression to search for.Your_Replacement_String
: The replacement string.g
: Global replacement flag. your-file.xml
: The name of the file on which you want to run the command.
Example
The following replaces the string “Resource” for the string, “Resources” in the register-account.xml
file.
sed -i 's/Resource/Resources/g' register-account.xml
Use cases
If you’ve identified your that need updating, but you don’t want to do a global update, you can update the string per file.