On Ubuntu Server, I use two different commands to find and replace a string in all files recursively in the current folder.
The first command is:
sudo find . -type f -print0 |\ xargs -0 -r sudo grep -F -l 'my-OLD-custom-string'
This commands searches all files recursively in the current folder and lists them. It doesn't do anything else except a search and list so that I can verify that these are the files that I want changed. Once I verify that all the files listed are the files that I want "my-OLD-custom-string" to be replaced with "my-NEW-custom-string", I can proceed to the second command.
The second command is:
sudo find . -type f -print0 |\ xargs -0 -r sudo grep -F -l --null 'my-OLD-custom-string' |\ xargs -0 -r sudo perl -pi~ -e 's/my-OLD-custom-string/my-NEW-custom-string/g'
This command will find "
my-OLD-custom-string
" in the files in the current directory recursively, replace them with "my-NEW-custom-string
", and leave my original unmodified files asfilename~
, for recovery, just in case.
I would like to put these commands into a bash script so that it looks reads/works like this:
$ cd ~/Downloads$ ls -latotal 40964drwxrwxr-x 2 Danran Danran 4096 Mar 2 19:17 .drwxr-x--- 20 Danran Danran 4096 Mar 13 15:02 ..-rw-r--r-- 1 Danran Danran 16380529 Sep 15 18:50 test_text1.txt-rw-r--r-- 1 Danran Danran 870 Feb 14 11:51 test_text2.txt-rw-r--r-- 1 Danran Danran 3129 Dec 22 2017 test_text3.txt-rw-r--r-- 1 Danran Danran 12693 Jan 20 2022 test_text4.txt-rwxr-xr-x 1 Danran Danran 0 Mar 13 15:59 custom_bash_script.sh$ cat test_text1.txtmy-OLD-custom-string$ ./custom_bash_script.shEnter the text string you are searching for:Text string here: my-OLD-custom-string[sudo] password for Danran: ****************Here are the listed files with your inputted text string:./test_text1.txtWould you like to replace the string "my-OLD-custom-string" in the above listed files?: yWhat do you want the new string to be?: my-NEW-custom-stringThe old string has now been replaced with the new string in the above requested files.$ cat test_text1.txtmy-NEW-custom-string
Here is the script that I have so far but it's not working at all...
#!/bin/shecho "Enter the text string you are searching for:"read -p "Text string here: " textstringoldsudo find . -type f -name "$textstringold"sudo find . -type f -print0 |\ xargs -0 -r sudo grep -F -l --null "$textstringold" |\ xargs -0 -r sudo perl -pi~ -e "s/$textstringold/$textstringnew/g"
Could someone please help me write this script to the desired specifications so that is is working as stated above? Any help would be much appreciated!