从shell脚本写入文件

时间:2015-07-02 07:30:57

标签: bash shell

我有一个文件myfile,其中包含以下文字:

self.Server('10.0.0.1', '00:00:00:00:00:01', 1)
self.Server('10.0.0.2', '00:00:00:00:00:01', 2)

我写了一个shell脚本来写入myfile。该脚本定义了一些变量:

hosts=100
servers=20
......

我想修改self.Server('10.0.0.x', '00:00:00:00:00:0x', x)中的行myfile并将其写为变量servers的值,其中x的范围从1到服务器的值(20 in in这种情况)。

注意:myfile可能已经有一些条目。例如,如果先前的servers值为4且新值为6,则只需要添加两个条目。此外,如果先前的值为6且新值为3,则需要删除前3个条目。

有人可以指导我如何实现它?

感谢。

2 个答案:

答案 0 :(得分:1)

#!/bin/bash
servers=20
for ((i=1; i<=servers; i++));; do
    printf "%s%02d%s\n" "self.Server('10.0.0.$i', '00:00:00:00:00:" "$i" "', $i)" >> myfile
done

运行结果:

self.Server('10.0.0.1', '00:00:00:00:00:01', 1)
self.Server('10.0.0.2', '00:00:00:00:00:02', 2)
self.Server('10.0.0.3', '00:00:00:00:00:03', 3)
self.Server('10.0.0.4', '00:00:00:00:00:04', 4)
self.Server('10.0.0.5', '00:00:00:00:00:05', 5)
self.Server('10.0.0.6', '00:00:00:00:00:06', 6)
self.Server('10.0.0.7', '00:00:00:00:00:07', 7)
self.Server('10.0.0.8', '00:00:00:00:00:08', 8)
self.Server('10.0.0.9', '00:00:00:00:00:09', 9)
self.Server('10.0.0.10', '00:00:00:00:00:10', 10)
self.Server('10.0.0.11', '00:00:00:00:00:11', 11)
self.Server('10.0.0.12', '00:00:00:00:00:12', 12)
self.Server('10.0.0.13', '00:00:00:00:00:13', 13)
self.Server('10.0.0.14', '00:00:00:00:00:14', 14)
self.Server('10.0.0.15', '00:00:00:00:00:15', 15)
self.Server('10.0.0.16', '00:00:00:00:00:16', 16)
self.Server('10.0.0.17', '00:00:00:00:00:17', 17)
self.Server('10.0.0.18', '00:00:00:00:00:18', 18)
self.Server('10.0.0.19', '00:00:00:00:00:19', 19)
self.Server('10.0.0.20', '00:00:00:00:00:20', 20)

答案 1 :(得分:1)

脚本看起来像:

#!/bin/bash

hosts=100
servers=20

for ((x = 1; x < $servers + 1; x++))
do
    temp=`printf "%02d" $x`
    echo "self.Server('10.0.0.$x', '00:00:00:00:00:$temp', $x)" >> myfile
done