bash find and replace string in file code example

Example 1: how to find and replace a string in a file using shell script

# replaces ALL(g i.e. global) ouccurences of "original_string" with "new_string", 
# in the file file_name.ext_name
sed -i 's/original_string/new_string/g' file_name.ext_name

Example 2: ubuntu command line replace word in files

sed -i 's/original/new/g' file.txt

Example 3: bash find and replace all files with specifc name with another file

find . -name "boom.txt" -exec cp ~/replace.txt {} \;

Example 4: bash search and replace text in file

# Basic syntax using awk:
awk '{gsub(regex, substitution_text, $field#); print $0;}' input_file
# Where:
#	- gsub is a function that replaces every regular expression (regex)
#		match with substitution_text. 
#	- $field# is optional but can be used to specify a particular field
#		where gsub should operate. (This is useful if you want to 
#		restrict the substitutions to a specific column)

# Example usage:
awk '{gsub(" ","",$0); print $0;}' input_file
# This replaces every space " " with nothing "", thereby eliminating all
# whitespace from the file