2016-08-09 49 views
1

我是新编写的shell脚本。我有以下shell脚本。我将使用循环动态替换一个字符串。如何使用shell脚本中的循环替换文件中的字符串?

for i in $(seq 1 5) 
    do 
     sed 's/counter/$i/g' AllMarkers.R > newfile.R 

    done 

但这个脚本$i代替12更换counter和....如果有人能告诉我怎样可以使用循环序列号更换counter我们将不胜感激。

回答

0

变量插值不在单引号内的字符串中执行。 ("Variable interpolation"是替代变量引用的功能的正式名称,例如“$ i”,它的值在字符串内部。)

如何解决这个问题的可能性很小。最常见的是这样的:

for i in $(seq 1 5) 
do 
    sed 's/counter/'$i'/g' AllMarkers.R > newfile.R 
done 

$i之前停止单引号字符串,把$i,然后恢复单引号的字符串。那将是变化:

# in case if $i might potentially contain spaces: 
sed 's/counter/'"$i"'/g' 

# in case if the whole expression to sed has no special characters: 
sed "s/counter/$i/g" 
相关问题