sed流編輯器——高級流控制 b 分支 t 測試
分支用於無條件轉移,測試用於有條件轉移
分支 branch
跳轉的位置與標籤相關聯
若是有標籤則跳轉到標籤所在的後面行繼續執行
若是沒有標籤則跳轉到腳本的結尾處
標籤 以冒號開始後接標籤名,不要在標籤名先後使用空格
跳轉到標籤指定位置
[root@localhost test]# grep myuser /etc/passwd
myuser:x:501:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser /etc/passwd|sed
':top;s/myuser/WUWEI/;/myuser/
b top;s/5/66/'
WUWEI:x:6601:501::/home/WUWEI:/bin/bash
命令分析:
[root@localhost test]# grep myuser /etc/passwd | sed '
:top; //設置標籤
s/myuser/WUWEI/; //將第一個myuser替換爲WUWEI
/myuser/b top; //若是匹配到有myuser,則跳轉到標籤top處
s/5/66/g' //當上一條不匹配時,執行本語句將5替換爲66
選擇執行一:
[root@localhost test]# grep myuser /etc/passwd|sed 's/myuser/WUWEI/;/myuser/b end;s/5/66/;:end;s/5/77/'
WUWEI:x:7701:501::/home/myuser:/bin/bash
命令分析:執行cmd1命令,再去匹配模式,若是匹配成功則跳轉到標籤end後執行cmd3命令,不然會按命令順序逐個執行cmd2和cmd3.
[root@localhost test]# grep myuser /etc/passwd|sed '
s/myuser/WUWEI/; cmd1
/myuser/b end;
s/5/66/; cmd2
:end;
s/5/77/' cmd3
選擇執行二:
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;
/myuser/b end;s/5/66/;b;:end;s/5/77/' //模式匹配成功類型
WUWEI:x:7701:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;
/myuser11/b end;s/5/66/;b;:end;s/5/77/' //模式匹配失敗類型
WUWEI:x:6601:501::/home/myuser:/bin/bash
命令分析:先執行cmd1命令;再進行模式匹配,若是匹配成功則跳轉到end標籤後執行cmd3命令,不然執行cmd2命令,再跳轉到腳本末尾
[root@localhost test]# grep myuser passwd |sed '
s/myuser/WUWEI/; cmd1
/myuser/b end;
s/5/66/; cmd2
b;
:end;
s/5/77/' cmd3
-----------------------
測試命令,若是前一個替換命令執行成功則跳轉到腳本末尾
測試示例:
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;t;s/home/HOME/;t;s/bash/BASH/'
WUWEI:x:501:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/AAmyuser/WUWEI/;t;s/home/HOME/;t;s/bash/BASH/'
myuser:x:501:501::/HOME/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/AAmyuser/WUWEI/;t;s/AAhome/HOME/;t;s/bash/BASH/'
myuser:x:501:501::/home/myuser:/bin/BASH
命令分析:若是cmd1命令執行成功,則跳到腳本末尾,若是cmd1命令執行不成,匹配執行cmd2命令,若是cmd2能執行成功,則跳轉到腳本末尾;不然匹配cmd3可否執行成功
[root@localhost test]# grep myuser passwd |sed '
s/myuser/WUWEI/; cmd1
t;
s/home/HOME/; cmd2
t;
s/bash/BASH/' cmd3
與標籤關聯,跳轉到指定標籤位置
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;
t end;s/home/HOME/;t;:end;s/bash/BASH/' WUWEI:x:501:501::/home/myuser:/bin/BASH 命令分析:若是cmd1命令執行成功,則跳轉到end標籤後面執行cmd3,不然匹配cmd2是否能執行成功,若是成功,則跳轉到腳本末尾,不然繼續匹配cmd3命令可否執行成功 [root@localhost test]# grep myuser passwd |sed ' s/myuser/WUWEI/; cmd1 t end; s/home/HOME/; cmd2 t; :end; s/bash/BASH/' cmd3