您的位置:首页 > 运维架构 > Shell

shell整理(39)====shell改变文本练习

2017-10-16 12:11 295 查看
http://blog.sina.com.cn/6699douding

我的新浪博客,里面有很多经典的脚本

题目环境:
**seq 20 > file,在1、3、5、9、14、18的上一行添加20个“=”。
file文件如下:

====================
1
2
====================
3
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在循环中不会被赋上值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  改变文本