0

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

我有 N 个目录(dir1,dir2 .. dirN),每个目录中都有文本文件 xyz.txt。我想用 line 编辑每个文件"probability = some variable"。“某个变量”应替换为来自 variable.txt 的 N 个变量列表中的相应值。

variable.txt 如下所示:

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

谁能帮我写一个bash脚本。

4

2 回答 2

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")
于 2013-10-22T14:50:46.780 回答
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
于 2013-10-22T16:11:38.923 回答