Linux下實現字符串截取,大致上能夠分爲兩種,使用命令實現截取,使用工具實現截取。具體截取方式以下:
html
a、#截取,能夠實現刪除左邊字符,保留右邊字符bash
從左邊第一個</>開始,刪除</>及以前的全部字符ide
str=http://www.baidu.com/index.html echo ${str#*/} # right first / 輸出: /www.baidu.com/index.html
b、##截取,能夠實現刪除左邊字符,保留右邊字符工具
從最右邊的</>開始,刪除</>及以前的全部字符ui
str=http://www.baidu.com/index.html echo ${str##*/} # rightest / 輸出: index.html
c、%截取,能夠實現刪除右邊字符,保留左邊字符spa
從右邊第一個</>開始刪除</>及右邊的全部字符htm
str=http://www.baidu.com/index.html echo ${str%/*} # left firft / 輸出: http://www.baidu.com
d、%%截取,能夠實現刪除右邊字符,保留左邊字符
進程
從左邊第一個</>開始刪除</>及右邊的全部字符字符串
str=http://www.baidu.com/index.html echo ${str%%/*} # leftest / 輸出: http:
e、區間截取get
截取第0~6個字符
str=http://www.baidu.com/index.html echo ${str:0:6} 輸出: http:/
f、正向區間截取到結束
截取從第7個字符開始到結束
str=http://www.baidu.com/index.html echo ${str:7} 輸出: www.baidu.com/index.html
g、反向區間截取
截取倒數第0到第7個字符的前5個
str=http://www.baidu.com/index.html echo ${str:0-7:5} 輸出: ex.ht
h、反向截取,到結束
從倒數第10個字符截取到字符串結束
str=http://www.baidu.com/index.html echo ${str:0-10} 輸出: index.html
i、使用cut命令實現字符串截取
cut [選項] 選項: -b ----> 字節 -c ----> 字符 -f ----> 域 已建立一個文件,內容以下: [muhui@localhost 3_26]$ cat file abcdefg 1234567 poiuytr
使用cut截取的例子以下:
[muhui@localhost 3_26]$ cat file | cut -b 3 c 3 i [muhui@localhost 3_26]$ cat file | cut -b -3 abc 123 poi [muhui@localhost 3_26]$ cat file | cut -b 3- cdefg 34567 iuytr [muhui@localhost 3_26]$ cat file | cut -b 3-5 cde 345 iuy [muhui@localhost 3_26]$ cat file | cut -b 3-5,7 cdeg 3457 iuyr
對於單字節而言,-b和-c彷佛做用是同樣的,可是若是文本內出現中文的狀況下,-c是能夠正確輸出一個漢字的,但使用-b選項輸出的倒是亂碼,由於一箇中文是兩個字節。爲了解決這個問題,一般-b選項和-n選項配合使用,-n用於告訴cut要截取的是n字節字符。
下面解釋域<-f>的做用。在/etc/passwd文件中保存了全部的用戶信息,仔細瞭解過的話,能夠發現,每一長串是經過 : 分隔開的。咱們能夠認爲該文件中的數據是以 : 分隔不一樣的域。指定域分隔符使用的是 -d 選項,-f後跟的數字格式和-b徹底一致。【cut的域分隔符只能是一個字符】
[muhui@localhost 3_26]$ cat /etc/passwd | head -n 5 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 [muhui@localhost 3_26]$ cat /etc/passwd | head -n 5 | cut -d : -f 1 root bin daemon adm lp
多餘說一點,看下面的例子
[muhui@localhost 3_26]$ ps PID TTY TIME CMD 5630 pts/2 00:00:00 bash 5739 pts/2 00:00:00 ps [muhui@localhost 3_26]$ ps | cut -b 4 I 3 4 4
明明只有三行,卻cut出了四個行內容,緣由就在與每一個命令其實都是父bash單首創建的一個進程,cut也不例外(內置命令除外)。
-----muhuizz整理