To find and replace text within a file on Linux, you can use various command-line tools such as sed, awk, or even grep combined with sed. Here’s how you can do it using sed, which is one of the most commonly used tools for this purpose:
sed -i 's/old_text/new_text/g' filename
Explanation:
-i: This option edits files in place. If you want to create a backup of the original file, you can use-i.bakinstead, which will create a backup with the extension.bak.'s/old_text/new_text/g': This is the substitution command in sed. It tells sed to substituteold_textwithnew_textglobally (i.e., all occurrences).filename: Replace this with the name of the file you want to modify.
For example, if you want to replace all occurrences of “hello” with “world” in a file named example.txt, you would use:
sed -i 's/hello/world/g' example.txt
Make sure to use caution when using the -i option, as it directly modifies the file. Always double-check the results to ensure they are as expected. If you want to preview the changes before actually modifying the file, you can omit the -i option and redirect the output to a different file:
sed 's/old_text/new_text/g' filename > new_filename
This command will perform the replacement and save the modified content to a new file called new_filename, leaving the original file unchanged.