Bash script to search and replace a string in a text file
bash script to search and replace a string in a text file with user input :
!/bin/bash
# script to search and raplace
filename="Sales.txt"
# ask for the search string
read -p "Enter the search string: " search
#ask for the replace string
read -p "Enter the replace string: " replace
if [[ $search != "" && $replace != "" ]]; then
sed -i "s/$search/$replace/" $filename
fi
‘-i’ option is used to modify the content of the original file with the replacement string if the search string exists in the file.
‘s’ indicates the substitute command.
‘search_string’ contains the string value that will be searched in the file for replacement.
‘replace_string’ contains the string value that will be used to replace the content of the file that matches the ‘search_string’ value.
‘filename’ contains the filename where the search and replace will be applied.
if your sed version supports the -i (inplace) option (check your manpage):
`man sed
stream editor for filtering and transforming text
Command ‘sed ’ not found, did you mean:
command ‘sed’ from deb sed (4.7-1)
Try: sudo apt install < deb name>
er is een man page , maar sed is niet installed ?? (verschillende tools ?)
sudo apt install sed
Reading package lists… Done
Building dependency tree
Reading state information… Done
sed is already the newest version (4.7-1).
0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.
which sed /usr/bin/sed
=> dubblle spatie na sed
'sed -i'
'sed -i'
CONSTANT error
sed: can’t read /mnt/temp/done.txt: No such file or directory
symlink issue ? nope zelfde fout in normale dir
set|grep sed
should show you where set is used in shell options, suggestions , filename completions etc.
And that’s it. Filename completion. simple as that.
bash tries to look up completions with sed and this triggers the error.
alternatives for sed
awk
using awk for search replcae text in file
awk ‘{gsub(“hello”, “bye”, $0); print}’ test.dat
awk ‘{gsub(“–stat:[progress]”, ” “, $0); print}’ /mnt/temp/done.txt > /mnt/temp/done2.txt
perl
perl -i -pe’s/hello/bye/g’ test.dat
perl -i -pe’s/–stat:[progress]/ /g’ /mnt/temp/done2.txt
ed
specified by POSIX:
printf ‘%s\n’ ‘%s/find/replace/g’ ‘x’ | ex file.txt
The x command is for “save and exit.” You can also use wq but x is shorter.
The % sign at the start of the substitute command means, “Apply this command to every line in the buffer.” You could use 1,$s/find/replace/g also.
One major difference between ex and sed is that sed is a stream editor. It only operates sequentially, line by line. ex is far more flexible than that, and in fact you can do interactive text file editing directly in ex. It is the immediate predecessor to vi.