Applying sed against a file from a list of values stored in a variable

Hi Forum.

I have the following challenge at work that I need to write a script for.

I have a file abc.txt with the following contents:

4560123456
4570987654
4580654321

I want to be able to search/replace in abc.txt - the first 4 characters anything starting with 4560 to 7777; 4570 to 8888; 4580 to 9999

I want to use a variable (if possible since in the future the list could be expanded and I would only need to expand the variable values without any additional coding):

str_search_list="4560/7777;4570/8888;4580/9999"

How would I loop thru the search string list and run the sed command on abc.txt?

With a bit of bash / ksh93 / zsh parameter expansion, try:

sed "s/^${str_search_list//;//;s/^}/" file

Result:

7777123456
8888987654
9999654321

Thanks I will give it a try

Also a sed multi-liner is easy to extend

sed "
s/^4560/7777/
s/^4570/8888/
s/^4580/9999/
" abc.txt

You can put the sed script to a variable

sedscript="
s/^4560/7777/
s/^4570/8888/
s/^4580/9999/
"
sed "$sedscript" abc.txt

or to a sedfile

sed -f sedfile abc.txt