Multiple search and replace in a file
May 24, 2010 Linux
Sometime we have to change a file by searching and replacing words on it.
But if we have too many search/replace pairs that is a huge work.
I’ve created a bash/shell script to which will do it automatically the replace. You can run it on Linux terminal.
This is the shell script file_replace.sh:
#!/bin/bash #in terminal: chmod 777 file_replace.sh for cur_line in `cat file_replace_data.txt`; do if [ "$(echo $cur_line | grep -o ',')" ] && [ "${cur_line:0:1}" ]; then #test if the line contain a , search=$(echo $cur_line | cut -d "," -f 1) #get the search string replace=$(echo $cur_line | cut -d "," -f 2) #get the replace string sed -i 's/'$search'/'$replace'/i' file_replace_text.txt #replace the string in the file fi done |
You have to have a file file_replace_data.txt containing your test, a file with search/replace words file_replace_data.txt, every line contain search word, a separator and the replace word
apple,beer potatoes,wine
So apple will be replaced with beer and potatoes with wine.
No related posts.
Tags: yo5oee



Leave a Reply