简体   繁体   中英

sed not working in for loop in shell script

I'm trying to replace all strings in 'toReplace.txt' matched with strings specified in 'replaceList.txt' one by one with an integer index using a for loop in bash shell script:

source='toReplace.txt'
map='replaceList.txt'
label=`cat $map`
index=1
for item in $label
do
  sed -i "s/$item/$index/g" $source
  index=$(( index + 1 ))
done

However the sed command works well out of the loop or in the command line console but once I put it in the for loop it doesn't work any more. If I run the above code, nothing actually changes with toReplace.txt.

Anyone has any idea what is wrong here? Many thanks!

Thanks all for the insight! An example of the .txt files

#toReplace.txt
3.66519 0
5.75959 0
1.39626 1.0472
5.23599 0.174533
1.91986 0.698132
1.0472 1.0472
2.61799 0.698132

#replaceList
0.174533
0.349066
0.523599
0.698132
0.872665
1.0472
1.22173
1.39626
1.5708
1.74533
1.91986
2.09439
2.26893
2.44346
2.61799

Basically I want to replace all float type numbers in toReplace.txt with the index (the # of line) of this float type number in replaceList.txt.

Output for @narendra's code

The output for @narendra's code is as above. Still nothing changed in my toReplace.txt. Anyone's got any idea what the issue is??

try as below ...

source='toReplace.txt'
map='replaceList.txt'
index=1
while read item
do
  # comment below echo once done testing
  echo "replacing $item with $index ..."
  sed -i "s/${item}/${index}/g" $source
  index=$(( index + 1 ))
done < $map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM