开发者

SED, using variables and in with an array

开发者 https://www.devze.com 2022-12-27 21:31 出处:网络
What I am trying to do is run the sed on multiple files in the directory Server_Upload, using variables:

What I am trying to do is run the sed on multiple files in the directory Server_Upload, using variables:

AB${count}

Corresponds, to some variables I made that look like:

  echo " AB1 = 2010-10-09Three " 
  echo " AB2 = 2009-3-09Foo " 
  echo " AB3 = Bar " 

And these correspond to each line which contains a word in master.ta, that needs changing in all the text files in Server_Upload.

If you get what I mean... great, I have tried to explain it the best I can, but if you are still miffed I'll give it another go as I found it really hard to convey what I mean.

cd Server_Upload
for fl in *.UP; do
     mv $fl $fl.old
     done

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<master.ta))
IFS="$saveIFS"
for i in "${array[@]}"
do
    sed "s/$i/AB${count}/g" $fl.old > $fl
    (( count++开发者_开发百科 ))
done

It runs, doesn't give me any errors, but it doesn't do what I want, so any ideas?


Your loop should look like this:

while read i
  do
  sed "s/$i/AB${count}/g" $fl.old > $fl
  (( count ++ ))
done < master.ta

I don't see a reason to use an array or something similar. Does this work for you?


It's not exactly clear to me what you are trying to do, but I believe you want something like: (untested)

do
eval repl=\$AB${count}
...

If you have a variable $AB3, and a variable $count, $AB${count} is the concatenation of $AB and $count (so if $AB is empty, it is the same as $count). You need to use eval to get the value of $AB3.


It looks like your sed command is dependent on $fl from inside the first for loop, even though the sed line is outside the for loop. If you're on a system where sed does in-place editing (the -i option), you might do:

count=1
while read i
  do
  sed -i'.old' -e "s/$i/AB${count}/g" Server_Upload/*.UP
  (( count ++ ))
done < master.ta

(This is the entire script, which incorporates Patrick's answer, as well.) This should substitute the text ABn for every occurrence of the text of the nth line of master.ta in any *.UP file.


Does it help if you move the first done statement from where it is to after the second done?

0

精彩评论

暂无评论...
验证码 换一张
取 消