天天看點

shell整理(39)====shell改變文本練習

題目環境:

**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==========

==========2==========

==========3==========

==========4==========

==========5==========

==========6==========

思路:用for循環來周遊這個檔案,如果說檔案中存在字元串為“========”号就替換成“=======數字=======”

,其中數字代表是第幾個“=======...”,是以我們需要一個遞增的變量來記錄“=====....”的個數。

***需求2

将序号1-2之間下面的數字追加到1.txt,2-3之間追加到2.txt,依次類推。

shell腳本如下

[root@localhost shell]# cat aa1.sh 

rm -rf *.txt

if [ "$i" = ==========$b========== ];then

continue

echo $i >> $(($b-1)).txt

[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 

[root@localhost shell]# cat 2.txt 

[root@localhost shell]# 

*****需求2錯誤總結

(1)if判斷那=========$b=======   可以用單引号或者不用引号,不能用雙引号,我也說不清楚是為什麼,寫腳本開高亮就好了

“=”  是比較字元串, -eq 一般用于邏輯運算,比較大小。

(2)一定要把b=$(($b+1))寫在continue上面,如果寫在下面,跳過“========$b=====”以後就直接比較下一個$i

後面的b=$(($b+1))就不看了,是以b在循環中不會被賦上值。

本文轉自 大雪兒 51CTO部落格,原文連結:http://blog.51cto.com/dingxue/1972748,如需轉載請自行聯系原作者