编辑一系列文件并从var列表中替换变量

时间:2013-10-22 14:38:56

标签: bash

我是一名生物学家,但对linux系统知之甚少。

我在每个目录中都有文本文件xyz.txt的N没有dir(dir1,dir2 .. dirN)。我想用行"probability = some variable"编辑每个文件。 “some variable”应该由来自variable.txt。

的N个变量列表中的相应值替换

variable.txt如下所示:

1 23
2 54
3 89
4 102
.
.
.
N 1000

任何人都可以帮我写一个bash脚本。

2 个答案:

答案 0 :(得分:0)

您可以使用此脚本:

# read variable.txt in an array
arr=( "" )
while read k v; do arr+=( $v ); done < variable.txt

# now start replacing xyz.txt in each subdir
i=1;
while read file; do
   repl=${arr[$i]}
   sed -i.bak "s/\(probability = \)some variable/\1$repl/" "$file"
   i=((i++))
done < <(find /some/path -name "xyz.txt")

答案 1 :(得分:0)

假设名称是事先知道的并且如您所描述的那样是后缀,您可以尝试以下脚本

while read number prob ;
do
    sed -i.bak "s/probability = .*$/probability = $prob/" dir$number/xyz.txt
done < variable.txt

演示:

$ cat t.sh 
#!/bin/bash

while read number prob ;
do
    sed -i.bak "s/probability = .*$/probability = $prob/" dir$number/xyz.txt
done < variable.txt
$ for i in {1..4} ; do cat -n dir$i/xyz.txt;  done
     1  tata
     2  probability = some value
     1  tata
     2  probability = some value
     1  tata
     2  probability = some value
     1  tata
     2  probability = some value
$ cat variable.txt 
1 23
2 54
3 89
4 102
$ ./t.sh 
$ for i in {1..4} ; do cat -n dir$i/xyz.txt;  done
     1  tata
     2  probability = 23
     1  tata
     2  probability = 54
     1  tata
     2  probability = 89
     1  tata
     2  probability = 102