sed基本用法 sed文本塊處理 、 sed高級應用

sed 文本編輯器(vim)
增,刪,改,查
特色:流處理器【逐行處理的流處理器】

各種編輯器notepad,notepad++,word,atom
vim,vi,gedit,sed

非交互的(sed)【手動修改vim】
1.模版虛擬機【img鏡像文件,xml的配置文件】

2.克隆【新的img鏡像,xml】
name
uuid
mac
disk file

vim abc.xml

3.clone-vm7
sed改的


yum -y install httpd
set /etc/httpd/conf/httpd.conf 【如果用vim,需要手動修改】
systemctl start httpd


vim a.txt 2g 大文件會down死
sed a.txt 2g
notepad a.txt 2g

語法格式

sed 選項 ‘定位指令’ 文件
sed -n "3p" /etc/passwd //3p 打印第三行//【sed有個默認輸出的功能】-n屏蔽默認輸出
[root@sanpao1 ~]# vim 1.txt
[root@sanpao1 ~]# sed "2p" 1.txt
1
2
2
3
4

1.定位
用行號定位、
vim 1.txt
1
2
3
4
5
6
7
8

[root@sanpao1 ~]# sed -n "2,3p" 1.txt
2
3
[root@sanpao1 ~]# sed -n "2p;4p" 1.txt
2
4
[root@sanpao1 ~]# sed -n "1~2p" 1.txt
1
3
5
7
[root@sanpao1 ~]# sed -n "2~2p" 1.txt
2
4
6
8
[root@sanpao1 ~]# sed -n "1~3p" 1.txt //步長3
1
4
7

man sed
addressess

2.正則
/正則/
sed -n “/root/p” 文件 //把有root的那一行打印
sed -n “/root/d” 文件 //-d刪除

[root@room3pc14 桌面]# sed -n "/root/p" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

腳本:自動管理

[root@sanpao1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=eth0
DEVICE=eth0
ONBOOT=yes

sed -n "/IPADDR/p" ///onboot是否開機

+++++++++++++++++++++++++++++++++++++++++++++++++++++++
3.指令
增【a,i】 sed "3i xxx" 文件 //a是在3後添加,i是在3前添加
[root@sanpao1 test]# sed "3a xxxx" a.txt //有默認輸出。先測試,再-i【修改原文件】。
1
2
3
xxxx
4
5
6
7
8
9
0
[root@sanpao1 test]# sed "3i xxxx" a.txt
1
2
xxxx
3
4
5
6
7
8
9
0
[root@sanpao1 test]# cat a.txt
1
2
3
4
5
6
7
8
9
0

[root@sanpao1 test]# sed -i "3i xxxx" a.txt 【確認好沒有問題,再添加-i】
[root@sanpao1 test]# cat a.txt
1
2
xxxx
3
4
5
6
7
8
9
0

刪 [d] sed '3d' 文件
sed "/[0-9]/d" 文件


改[c,s] [change,substitute] 【注意:c修改一整行,s僅修改某個關鍵詞】
sed "3c xxx" 文件
sed "/正則/c 內容"
sed "3【3可加可不加,僅替換第三行】s/old/new/" 文件 s 關鍵詞替換
sed -r【擴展正則】"s/[0-9]/new/" 文件
sed “s/x//” 文件 把x替換成空,即刪除【變相刪除】
[root@sanpao1 test]# sed "3c vv" a.txt //不管第三行是什麼,都改成vv
1
2
vv
4
5
6
[root@sanpao1 test]# sed "c xxxx" a.txt //替換全文0
xxxx
xxxx
xxxx

[root@sanpao1 test]# sed "s/2010/xxxx/" a.txt //默認替換每行第一個
xxxx 2011 2010
2001 2006 xxxx
xxxx 2010 2010
[root@sanpao1 test]# sed "s/2010/xxxx/2" a.txt //替換每行第二個
2010 2011 xxxx
2001 2006 2010
2010 xxxx 2010
[root@sanpao1 test]# sed "3s/2010/xxxx/2" a.txt //替換第三行第二個
2010 2011 2010
2001 2006 2010
2010 xxxx 2010
[root@sanpao1 test]# sed "s/2010/xxxx/g" a.txt //替換所有
xxxx 2011 xxxx
2001 2006 xxxx
xxxx xxxx xxxx

[root@sanpao1 test]# sed "s/$/ xxx/" a.txt //$在每行的行尾添加xxx
2010 2011 2010 xxx
2001 2006 2010 xxx
2010 2010 2010 xxx


[root@sanpao1 test]# egrep "[0-9]{1,}" /etc/passwd //\在擴展正則裏面不識別
[root@sanpao1 test]# grep "[0-9]{1,}" /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt


[root@room3pc14 test]# cp /etc/libvirt/qemu/desktop.xml libvirt.txt
複製一個素材文件,修改以下信息
name,uuid,mac,source
NAME,UUID,MAC,source
grep -i "name" 文件 【先觀察數據】

sed -n "s/old/new/p" 文件 【方便驗證】
[root@room3pc14 test]# sed -i "/<name>/c <name>abc</name>" libvirt.txt
[root@room3pc14 test]# grep -i "<name>" libvirt.txt
<name>abc</name>

[root@room3pc14 test]# sed -i "/<name>/s/>.*</>bcd</" libvirt.txt ###
[root@room3pc14 test]# grep -i "<name>" libvirt.txt
<name>bcd</name>

read -p "請輸入虛擬機編號:" num
sed "s/old/new"
sed "s/desktop/clone-v$num"

查p

sed “a,i,c,s,d,p”

sed 選項“定位指令” 文件

1.行號
2./正則/

vim a,i,s,o新建,r替換,x,dd,yy,p

sed&awk【書】【更多的正則表達式】

vim abc.conf
Documentroot /var/www/html

把/var/www/html---》/data/html

sed "11s/ \/var/www/html\ / \/data/html\"
sed "11s/【替換開始】\【爲/轉義】/var/www/html\/【替換結束】\【轉義】/data/html/【結尾】 //【這樣太亂了!!最好不這麼用】

sed -n s/ / /p 搭配用 顯示替換的那一行

sed "s# # #" 文件
sed "s, , , " 文件
sed "s! ! !" 文件
【sed 中的///可以替換成任意符號】
sed “指令” 文件
/etc/httpd/conf/httpd.conf //可以拿這個文件聯繫

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

163面試題!!!
sed ‘s9\98\9\997\98\99’ 文件

sed ‘s9 \98\9\9 9 7\98\9 9’ 文件

讀取用戶輸入的密碼
判斷密碼對不對,如果輸入錯三次,則退出

for i in {1..3}
do
read -p "請輸入密碼" 密碼
if [ $pass == "abc" ];then
echo “對”
exit
done
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

理解
正則()保留
abcttabcxxabcqqabcopabc
grep "(abc)tt\1xx\1qq1\1op\1" a.txt

複製

vim ifcfg-eth0
IPADDR=192.168.4.5
GATWAY=192.168.4.254
DNS=1.1.1.1

sed "/IPADDR/s/192.168.4.5/1.1.1.1/"
sed "s/(IPADDR=)./\IPADDR=12.2.2.2/"
sed "s/(IPADDR=)【複製】.
/ \IPADDR=1 【粘貼()裏面的內容】 2.2.2.2/"

sed "/IPADDR/s/192.168.4.(.)/1.1.1.\1/"
sed "/IPADDR/s/192.168.4.(.
)【保留】/1.1.1.\1【粘貼】/"

聯繫

hello the world
ni hao ma nb
chi le ma
yue ma

要求:將每一行的第一個字符與最後一個字符對調一下
提示:什麼是第一個字符,什麼是最後一個字符
保留()

sed -r "s/old/new/" 文件

^.開頭
.*中間的內容
.$ 結尾

sed -r "s/ (^.) (.) (.$)/ \3\2\1" #### (^.)是1,(.)是2,(.$)是3

要求:將每一行的第2個字符與倒數第2個字符對調一下
提示:什麼是第2個字符,什麼是倒數第2個字符
保留()

[root@room3pc14 test]# sed -ri "s/(^.)(.)(.*)(.)(.$)/\1\4\3\2\5/" a.txt

^..第二個字符
..$ 倒數第二個字符


[root@room3pc14 test]# sed -n "2,+2 p" a.txt
從第二行開始,包含第二行,再加2行

sed -n "p,n" a.txt // 讀基數行 ,
sed -n "p,n" a.txt //讀偶數行

sed -n "$=" a.txt //統計一共有幾行

[root@room3pc14 test]# sed -n "$=" a.txt
4
[root@room3pc14 test]# wc -l /etc/passwd
46 /etc/passwd
[root@room3pc14 test]# cat /etc/passwd | wc -l
46

sed "s/^/#/" 文件 //加註釋
sed "s/#//" 文件 //去註釋122

vim
:r
:w /a.txt 另存到

sed "r /etc/hosts" a.txt 倒入

sed "2w c.txt" a.txt //把a文件存到c文件裏

Top
NSD SHELL DAY05

案例1:sed基本用法
案例2:使用sed修改系統配置
案例3:sed多行文本處理
案例4:sed綜合腳本應用

1 案例1:sed基本用法
1.1 問題

本案例要求熟悉sed命令的p、d、s等常見操作,並結合正則表達式,完成以下任務:

刪除文件中每行的第二個、最後一個字符
將文件中每行的第一個、第二個字符互換
刪除文件中所有的數字、行首的空格
爲文件中每個大寫字母添加括號

1.2 方案

sed文本處理工具的用法:

用法1:前置命令 | sed  [選項]  '編輯指令'
用法2:sed  [選項]  '編輯指令'  文件.. ..

相關說明如下:

“編輯指令”可以爲增刪改查等指令
“定址符”用來定義需要操作的文本,由“[地址1 [,地址2]]組成
未指定“定址符”時,默認處理所有文本

1.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:認識sed工具的基本選項

1)sed命令的 -n 選項

執行p打印等過濾操作時,希望看到的是符合條件的文本。但不使用任何選項時,默認會將原始文本一併輸出,從而干擾過濾效果。比如,嘗試用sed輸出/etc/rc.local的第1行:

[root@svr5 ~]# sed '1p' /etc/rc.local
#!/bin/sh
#!/bin/sh
#
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

可以發現所有的行都被顯示出來了。—— 正確的用法應該添加 -n 選項,這樣就可以只顯示第1行了:

[root@svr5 ~]# sed -n '1p' /etc/rc.local
#!/bin/s

而在執行d刪除等過濾操作時,希望看到的是刪除符合條件的文本之後還能夠被保留下來的文本,所以這時候就不應該使用 -n 選項了。比如,刪除/etc/rc.local文件的第1-4行文本:

[root@svr5 ~]# sed '1,4d' /etc/rc.local
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local

2)sed命令的 -i 選項

正常情況下,sed命令所做的處理只是把操作結果(包括打印、刪除等)輸出到當前終端屏幕,而並不會對原始文件做任何更改:

[root@svr5 ~]# sed '1,4d' rclocal.txt              //刪除第1~4行,輸出結果
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
[root@svr5 ~]# cat rclocal.txt                  //查看原始文本,並未改動

若希望直接修改文件內容,應添加選項 -i 。

比如,直接刪除rcloal.txt文件的第1~4行,不輸出結果:

[root@svr5 ~]# sed -i '1,4d' rclocal.txt            //刪除操作
[root@svr5 ~]# cat rclocal.txt                      //確認刪除結果

下文中關於使用sed修改文件的示例中,爲了避免大家在練習過程中因誤操作導致系統故障,部分命令省略 –i 選項,不再逐一說明。需要時,大家可自行加上此選項。

3)多個指令可以使用分號隔離

用分號來隔離多個操作(如果有定址條件,則應該使用{ }括起來),比如:

[root@svr5 ~]# sed -n '1p;4p' /etc/rc.local
#!/bin/sh
# You can put your own initialization stuff in here if you don't

或者:

[root@svr5 ~]# sed -n '{1p;4p}' /etc/rc.local
#!/bin/sh
# You can put your own initialization stuff in here if you don't

步驟二:認識sed工具的p輸出操作

先創建一個練習用的測試文件,每一行之前添加行號,方便練習時查看效果:

[root@svr5 ~]# cat -n /etc/rc.local > rclocal.txt
[root@svr5 ~]# cat rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

1)輸出所有行,相當於cat命令。

[root@svr5 ~]# sed -n 'p' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

2)輸出第4行。

[root@svr5 ~]# sed -n '4p' rclocal.txt
     4  # You can put your own initialization stuff in here if you don't

3)輸出第4~7行。

[root@svr5 ~]# sed -n '4,7p' rclocal.txt
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

4)輸出第4行和第7行。

[root@svr5 ~]# sed -n '4p;7p' rclocal.txt
     4  # You can put your own initialization stuff in here if you don't
     7  touch /var/lock/subsys/local

5)輸出第2行及之後的3行。

[root@svr5 ~]# sed -n '2,+3p' rclocal.txt
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.

6)輸出以local結尾的行。

[root@svr5 ~]# sed -n '/local$/p' rclocal.txt
     7  touch /var/lock/subsys/local

7)輸出奇數行。

[root@svr5 ~]# sed -n 'p;n' rclocal.txt
     1  #!/bin/sh
     3  # This script will be executed *after* all the other init scripts.
     5  # want to do the full Sys V style init stuff.
     7  touch /var/lock/subsys/local

8)輸出偶數行。

[root@svr5 ~]# sed -n 'n;p' rclocal.txt
     2  #
     4  # You can put your own initialization stuff in here if you don't
     6

9)從第5行輸出到最後一行。

[root@svr5 ~]# sed -n '5,$p' rclocal.txt
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

10)輸出文本的行數。

[root@svr5 ~]# sed -n '$=' rclocal.txt
7

步驟三:認識sed工具的d輸出操作

還以rclocal.txt文件爲例,文件內容如下所示:

[root@svr5 ~]# cat rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

1)刪除第3~5行文本

[root@svr5 ~]# sed '3,5d' rclocal.txt
     1  #!/bin/sh
     2  #
     6
     7  touch /var/lock/subsys/local

2)刪除所有包含“init”的行

[root@svr5 ~]# sed '/init/d' rclocal.txt
     1  #!/bin/sh
     2  #
     6
     7  touch /var/lock/subsys/local

3)刪除所有包含“init”的行、所有包含“bin”的行

[root@svr5 ~]# sed '/init/d;/bin/d' rclocal.txt
     2  #
     6
     7  touch /var/lock/subsys/local

4)刪除不包括“init”的行

[root@svr5 ~]# sed '/init/!d' rclocal.txt
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.

這個實際效果相當於只顯示包含“init”的行:

[root@svr5 ~]# sed -n '/init/p' rclocal.txt
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.

5)刪除文件的最後一行

[root@svr5 ~]# sed '$d' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6

6)刪除文件中的空行

手動新建一個測試文件:

[root@svr5 ~]# vim blankline.txt
abc
def
hijklmn
hello world
I am here
end

刪除所有空行:

[root@svr5 ~]# sed '/^$/d' blankline.txt
abc
def
hijklmn
hello world
I am here
end

步驟四:認識sed工具的s替換操作

還以rclocal.txt文件爲例,文件內容如下所示:

[root@svr5 ~]# cat rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

1)將所有行中的第一個“ll”(如果有的話)替換爲“TARENA”。

[root@svr5 ~]# sed 's/ll/TARENA/' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script wiTARENA be executed *after* all the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the fuTARENA Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

2)將所有的“ll”(如果有的話)替換爲“TARENA”。

 [root@svr5 ~]# sed 's/ll/TARENA/g' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script wiTARENA be executed *after* aTARENA the other init scripts.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the fuTARENA Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

3)將第3行內的第2個“script”替換爲“SCRIPT”。

[root@svr5 ~]# sed '3s/script/SCRIPT/2' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other init SCRIPTs.
     4  # You can put your own initialization stuff in here if you don't
     5  # want to do the full Sys V style init stuff.
     6
     7  touch /var/lock/subsys/local

4)刪除文件內指定的字符串(替換爲空)。

刪除所有的“init”字符串:

[root@svr5 ~]# sed 's/init//g' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This script will be executed *after* all the other  scripts.
     4  # You can put your own ialization stuff in here if you don't
     5  # want to do the full Sys V style  stuff.
     6
     7  touch /var/lock/subsys/local

刪除所有的“script”、所有的“stuff”、所有的字母e,或者的關係用轉義方式 | 來表示:

[root@svr5 ~]# sed 's/script\|stuff\|e//g' rclocal.txt
     1  #!/bin/sh
     2  #
     3  # This  will b xcutd *aftr* all th othr init s.
     4  # You can put your own initialization  in hr if you don't
     5  # want to do th full Sys V styl init .
     6
     7  touch /var/lock/subsys/local

5)配置行的註釋、解除註釋。

以真實文件/etc/rc.local爲例,文件內容如下:

[root@svr5 ~]# cat /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local

解除/etc/rc.local文件第3~5行的註釋(去掉開頭的 # ):

[root@svr5 ~]# sed '3,5s/^#//' /etc/rc.local
#!/bin/sh
#
 This script will be executed *after* all the other init scripts.
 You can put your own initialization stuff in here if you don't
 want to do the full Sys V style init stuff.
touch /var/lock/subsys/local

將/etc/rc.local文件的第6~7行註釋掉(行首添加 # ):

[root@svr5 ~]# sed '6,7s/^/#/' /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
#
#touch /var/lock/subsys/local

步驟五:利用sed完成本例要求的任務

參考數據文件內容如下:

[root@svr5 ~]# cat nssw.txt
An example Name Service Switch config file. This file should be
sorted with the most-used services at the beginning.
#
The entry '[NOTFOUND=return]' means that the search for an
entry should stop if the search in the previous entry turned
up nothing. Note that if the search failed due to some other reason
(like no NIS server responding) then the search continues with the

本小節的操作使用nssw.txt作爲測試文件。

1)刪除文件中每行的第二個、最後一個字符

分兩次替換操作,第一次替換掉第2個字符,第二次替換掉最後一個字符:

[root@svr5 ~]# sed 's/.//2;s/.$//' nssw.txt 
A example Name Service Switch config file. This file should b
srted with the most-used services at the beginning
#
Te entry '[NOTFOUND=return]' means that the search for a
etry should stop if the search in the previous entry turne
u nothing. Note that if the search failed due to some other reaso
(ike no NIS server responding) then the search continues with th

2)將文件中每行的第一個、第二個字符互換

每行文本拆分爲“第1個字符”、“第2個字符”、“剩下的所有字符”三個部分,然後通過替換操作重排順序爲“2-1-3”:

[root@svr5 ~]# sed -r 's/^(.)(.)(.*)/\2\1\3/' nssw.txt
nA example Name Service Switch config file. This file should be
osrted with the most-used services at the beginning.
#
hTe entry '[NOTFOUND=return]' means that the search for an
netry should stop if the search in the previous entry turned
pu nothing. Note that if the search failed due to some other reason
l(ike n up . Note that if the search failed due to some other
(like  NIS server responding) then the search continues with

3)刪除文件中所有的數字、行首的空格

因原文件內沒有數字,行首也沒有空格,這裏稍作做一點處理,生成一個新測試文件:

[root@svr5 ~]# sed 's/o/o7/;s/l/l4/;3,5s/^/  /' nssw.txt > nssw2.txt
[root@svr5 ~]# cat nssw2.txt
An exampl4e Name Service Switch co7nfig file. This file should be
so7rted with the most-used services at the beginning.
  #
  The entry '[NOTFOUND=return]' means that the search fo7r an
  entry sho7ul4d stop if the search in the previous entry turned
up no7thing. Note that if the search fail4ed due to some other reason
(l4ike no7 NIS server responding) then the search continues with the

以nssw2.txt文件爲例,刪除所有數字、行首空格的操作如下:

[root@svr5 ~]# sed -r 's/[0-9]//g;s/^( )+//' nssw2.txt

4)爲文件中每個大寫字母添加括號

使用“&”可調用s替換操作中的整個查找串,所以可參考下列操作解決:

[root@svr5 ~]# sed 's/[A-Z]/(&)/g' nssw.txt
(A)n example (N)ame (S)ervice (S)witch config file. (T)his file should be
sorted with the most-used services at the beginning.
#
(T)he entry '[(N)(O)(T)(F)(O)(U)(N)(D)=return]' means that the search for an
entry should stop if the search in the previous entry turned
up nothing. (N)ote that if the search failed due to some other reason
(like no (N)(I)(S) server responding) then the search continues with the

2 案例2:使用sed修改系統配置
2.1 問題

本案例要求熟悉課上的sed應用案例,並編寫腳本anonftp.sh,實現以下功能:

通過yum安裝vsftpd軟件包
修改vsftpd服務配置,開啓匿名上傳
調整/var/ftp/pub目錄權限,允許ftp寫入
啓動vsftpd服務,並設置開機自運行

2.2 步驟

實現此案例需要按照如下步驟進行。

步驟一:認識課堂上的sed練習

1)修改默認運行級別

將默認運行級別修改爲5,確認修改結果:

[root@svr5 ~]# sed -i '/^id:/s/3/5/' /etc/inittab
[root@svr5 ~]# grep "^id:" /etc/inittab
id:5:initdefault:

再改回去:

[root@svr5 ~]# sed -i '/^id:/s/5/3/' /etc/inittab
[root@svr5 ~]# grep "^id:" /etc/inittab
id:3:initdefault:

2)修改IP地址的網段部分,主機地址不變。

直接修改網卡eth0的配置文件,檢查原有的配置內容:

[root@svr5 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=none
HWADDR=00:0c:29:82:09:e9
ONBOOT=yes
NETMASK=255.255.255.0
IPADDR=192.168.4.4
TYPE=Ethernet

若希望將IP地址192.168.4.4修改爲172.16.16.4,則應該定位到“IPADDR”所在的行,執行相應的替換(僅測試,尚未修改):

[root@svr5 ~]# sed '/^IPADDR/s/192.168.4.4/172.16.16.4/' \
  /etc/sysconfig/network-scripts/ifcfg-eth0 | grep "^IPADDR"
IPADDR=172.16.16.4

要求只修改網段地址時,可以利用擴展正則表達式的 \1、\2、……等調用,分別對應此前第1個、第2個、…… 以 ()包圍的表達式所匹配的內容。

所以上述操作可以改爲如下(啓用擴展匹配應添加 -r 選項):

[root@svr5 ~]# sed -r -i '/^IPADDR/s/192.168.4.(.*)/172.16.16.\1/' \
/etc/sysconfig/network-scripts/ifcfg-eth0

確認修改結果:

[root@svr5 ~]# grep "^IPADDR" /etc/sysconfig/network-scripts/ifcfg-eth0
IPADDR=172.16.16.4

再改回去:

[root@svr5 ~]# sed -r -i '/^IPADDR/s/172.16.16.(.*)/192.168.4.\1/' \
/etc/sysconfig/network-scripts/ifcfg-eth0
[root@svr5 ~]# grep "^IPADDR" /etc/sysconfig/network-scripts/ifcfg-eth0
IPADDR=192.168.4.4

3)調整httpd服務配置,更改網站根目錄

由於需要替換的字符串中有 / ,爲了避免與sed替換操作的分隔混淆,可以使用其他字符作爲替換分隔,比如可改用“s#old#new#”的方式實現替換:

[root@svr5 ~]# sed -i 's#/var/www/html#/opt/wwwroot#' \
/etc/httpd/conf/httpd.conf
[root@svr5 ~]# grep "^DocumentRoot" /etc/httpd/conf/httpd.conf
DocumentRoot "/opt/wwwroot"

若要恢復,可再改回去:

[root@svr5 ~]# sed -i 's#/opt/wwwroot#/var/www/html#'\
 /etc/httpd/conf/httpd.conf
[root@svr5 ~]# grep "^DocumentRoot" /etc/httpd/conf/httpd.conf
DocumentRoot "/var/www/html"

步驟二:編寫anonftp.sh腳本,用來裝配匿名FTP服務

1)任務需求及思路分析

vsftpd服務的安裝、改目錄權限、起服務等操作可以直接寫在腳本中。

修改vsftpd.conf配置的工作可以使用sed命令,根據默認配置,只需要定位到以#anon開頭的行,去掉開頭的註釋即可。

2)根據實現思路編寫腳本文件

[root@svr5 ~]# vim anonftp.sh
#!/bin/bash
yum -y install vsftpd                             //安裝vsftpd軟件
cp /etc/vsftpd/vsftpd.conf{,.bak}                  //備份默認的配置文件
sed -i "/^#anon/s/^#//" /etc/vsftpd/vsftpd.conf      //修改服務配置
chown ftp /var/ftp/pub                              //調整目錄權限
/etc/init.d/vsftpd restart                          //啓動服務
chkconfig vsftpd on                                  //設爲自動運行
[root@svr5 ~]# chmod +x anonftp.sh

3)驗證、測試腳本

運行腳本anonftp.sh:

[root@svr5 ~]# ./anonftp.sh
.. ..
Installed:
  vsftpd.x86_64 0:2.0.5-28.el5
Complete!
關閉 vsftpd:                                              [失敗]
爲 vsftpd 啓動 vsftpd:                                    [確定]

使用ftp登錄服務,測試是否可以上傳:

[root@svr5 ~]# ftp localhost                          //本機訪問測試
Connected to localhost.localdomain.
220 (vsFTPd 2.0.5)
530 Please login with USER and PASS.
530 Please login with USER and PASS.
KERBEROS_V4 rejected as an authentication type
Name (localhost:root): ftp                          //匿名登錄
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> cd pub                                          //切換到 pub/ 目錄
250 Directory successfully changed.
ftp> put install.log                          //上傳當前目錄下的install.log 文件
local: install.log remote: install.log
227 Entering Passive Mode (127,0,0,1,192,127)
150 Ok to send data.
226 File receive OK.
33139 bytes sent in 0.0065 seconds (5e+03 Kbytes/s)
ftp> quit                                          //斷開FTP連接
221 Goodbye.

查看/var/ftp/pub新上傳的文件:

[root@svr5 ~]# ls -lh /var/ftp/pub/
總計 36K
-rw------- 1 ftp ftp 33K 12-13 18:25 install.log

3 案例3:sed多行文本處理
3.1 問題

本案例要求使用sed工具來完成下列任務操作:

修改主機名配置文件
修改hosts文件,添加兩條映射記錄:192.168.4.5 與 svr5.tarena.com、svr5,還有119.75.217.56與www.baidu.com

3.2 方案

sed工具的多行文本處理操作:

i:在指定的行之前插入文本
a:在指定的行之後追加文本
c:替換指定的行

3.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:修改主機名配置文件

1)確認修改前的配置

[root@svr5 ~]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=svr5.tarena.com

2)使用sed修改主機名配置所在行的內容(c整行替換)

[root@svr5 ~]# sed  '/^HOSTNAME/cHOSTNAME=mysvr.tarena.com' /etc/sysconfig/network 

步驟二:修改hosts文件,添加新的記錄

1)確認修改前的配置

[root@svr5 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

2)使用sed修改hosts文件,添加兩行新紀錄(a追加)

[root@svr5 ~]# sed  -i  '$a192.168.4.5  svr5.tarena.com svr5\
> 119.75.217.56  www.baidu.com' /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.4.5  svr5.tarena.com svr5
119.75.217.56  www.baidu.com

4 案例4:sed綜合腳本應用
4.1 問題

本案例要求編寫腳本getupwd.sh,實現以下需求:

找到使用bash作登錄Shell的本地用戶
列出這些用戶的shadow密碼記錄
按每行“用戶名 --> 密碼記錄”保存到getupwd.log,如圖-1所示

圖-1
4.2 方案

基本思路如下:

先用sed工具取出登錄Shell爲/bin/bash的用戶記錄,保存爲臨時文件/tmp/urec.tmp,並計算記錄數量
再結合while循環遍歷取得的賬號記錄,逐行進行處理
針對每一行用戶記錄,採用掐頭去尾的方式獲得用戶名、密碼字串
按照指定格式追加到/tmp/getuupwd.log文件
結束循環後刪除臨時文件,報告分析結果

4.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:編寫getupwd.sh腳本

[root@svr5 ~]# vim ./getupwd.sh  
#/bin/bash
> /tmp/getupwd.log                                     ## 創建空文件
sed -n '/:\/bin\/bash$/w /tmp/urec.tmp' /etc/passwd      ## 提取符合條件的賬號記錄
UNUM=$(egrep -c '.' /tmp/urec.tmp)                   ## 取得記錄個數
while [ ${i:=1} -le $UNUM ]                         ## 從第1行開始,遍歷賬號記錄
do
    UREC=$(sed -n "${i}p" /tmp/urec.tmp)              ## 取指定行數的記錄
    NAME=${UREC%%:*}                                 ## 截取用戶名(記錄去尾)
    PREC=$(sed -n "/^$NAME:/p" /etc/shadow)          ## 查找與用戶名對應的密碼記錄
    PASS=${PREC#*:}                                  ## 掐頭
    PASS=${PASS%%:*}                                ## 去尾,只留下密碼記錄
    echo "$NAME --> $PASS" >> /tmp/getupwd.log         ## 保存結果
    let i++                                           ## 自增1,轉下一次循環
done
/bin/rm -rf /tmp/urec.tmp                           ## 刪除臨時文件
echo "用戶分析完畢,請查閱文件 /tmp/getupwd.log"         ## 完成後提示
[root@svr5 ~]# chmod +x ./getupwd.sh 

步驟二:測試、驗證執行結果

[root@svr5 ~]# ./getupwd.sh     
用戶分析完畢,請查閱文件 /tmp/getupwd.log
[root@svr5 ~]# less /tmp/getupwd.log 
root --> $6$IWgMYmRACwdbfwBo$dr8Yn983nswiJVw0dTMjzbDvSLeCd1GMYjbvsDiFEkL8jnXOLcocBQypOCr4C6BRxNowIxjh6U2qeFU0u1LST/
zengye --> $6$Qb37LOdzRl5995PI$L0zTOgnhGz8ihWkW81J.5XhPp/l7x2./Me2ag0S8tRndCBL9nIjHIKkUKulHxJ6TXyHYmffbVgUT6pbSwf8O71
clamav --> !!
mysql --> !!
abc --> !!
.. ..

從上述參考腳本可以發現,使用sed來實現字段提取會比較複雜。下一章課程將會學到awk命令,屆時可以通過更簡單的方法來改進此腳本內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章