加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 09:24:17 所属栏目:安全 来源:网络整理
导读: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 =====

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在循环中不会被赋上值。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读