Linux下實現字符串截取方法總結

    Linux下實現字符串截取,大體上可以分爲兩種,使用命令實現截取,使用工具實現截取。具體截取方式如下:


     a、#截取,可以實現刪除左邊字符,保留右邊字符

     從左邊第一個</>開始,刪除</>及之前的所有字符

str=http://www.baidu.com/index.html
echo ${str#*/}        # right first /
輸出:
     /www.baidu.com/index.html


     b、##截取,可以實現刪除左邊字符,保留右邊字符

     從最右邊的</>開始,刪除</>及之前的所有字符

str=http://www.baidu.com/index.html
echo ${str##*/}        # rightest /
輸出:
     index.html


     c、%截取,可以實現刪除右邊字符,保留左邊字符

     從右邊第一個</>開始刪除</>及右邊的所有字符

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、區間截取

     截取第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整理

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