http://blog.sina.com.cn/6699douding
shell
个人新浪博客,里面有不少经典的脚本bash
题目环境:ide
**seq 20 > file,在一、三、五、九、1四、18的上一行添加20个“=”。spa
file文件以下:blog
====================字符串
1get
2博客
====================it
3io
4
====================
5
6
7
8
====================
9
10
11
12
13
====================
14
15
16
17
====================
18
19
20
***需求1
在每个“==================”之间插入序号,例如第一个等于号“============1==========”
shell 代码以下
[root@localhost shell]# cat aa.sh
#!/bin/bash
b=1
for i in `cat file`
do
if [ "$i" = "====================" ];then
echo $i | sed 's/====================/=========='$b'==========/g'
b=$(($b+1))
else
echo "$i"
fi
done
执行结果以下
==========1==========
1
2
==========2==========
3
4
==========3==========
5
6
7
8
==========4==========
9
10
11
12
13
==========5==========
14
15
16
17
==========6==========
18
19
20
思路:用for循环来遍历这个文件,若是说文件中存在字符串为“========”号就替换成“=======数字=======”
,其中数字表明是第几个“=======...”,因此咱们须要一个递增的变量来记录“=====....”的个数。
***需求2
将序号1-2之间下面的数字追加到1.txt,2-3之间追加到2.txt,依次类推。
shell脚本以下
[root@localhost shell]# cat aa1.sh
#!/bin/bash
rm -rf *.txt
b=1
for i in `cat file`
do
if [ "$i" = ==========$b========== ];then
b=$(($b+1))
continue
else
echo $i >> $(($b-1)).txt
fi
done
执行结果以下
[root@localhost shell]# ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt aa1.sh aa.sh file file1
[root@localhost shell]# cat 1.txt
1
2
[root@localhost shell]# cat 2.txt
3
4
[root@localhost shell]#
*****需求2错误总结
(1)if判断那=========$b======= 能够用单引号或者不用引号,不能用双引号,我也说不清楚是为何,写脚本开高亮就行了
“=” 是比较字符串, -eq 通常用于逻辑运算,比较大小。
(2)必定要把b=$(($b+1))写在continue上面,若是写在下面,跳过“========$b=====”之后就直接比较下一个$i
后面的b=$(($b+1))就不看了,因此b在循环中不会被赋上值。