shell -- cut用法

來源:互聯網
上載者:User

標籤:

cut命令可以從一個文字檔或者文字資料流中提取文本列。

cut文法
[[email protected] ~]# cut -d ‘分隔字元‘ -f fields <==用於有特定分隔字元
[[email protected] ~]# cut -c 字元區間               <==用於排列整齊的資訊
選項與參數:
-d  :後面接分隔字元。與 -f 一起使用;
-f  :依據 -d 的分隔字元將一段資訊分割成為數段,用 -f 取出第幾段的意思;
-c  :以字元 (characters) 的單位取出固定字元區間;

PATH 變數如下
[[email protected] ~]# echo $PATH
/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/games
# 1 | 2       | 3   | 4       | 5            | 6            | 7

將 PATH 變數取出,我要找出第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 5
/usr/local/bin
 
將 PATH 變數取出,我要找出第三和第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 3,5
/sbin:/usr/local/bin

將 PATH 變數取出,我要找出第三到最後一個路徑。
echo $PATH | cut -d ‘:‘ -f 3-
/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/games
 
將 PATH 變數取出,我要找出第一到第三個路徑。
#echo $PATH | cut -d ‘:‘ -f 1-3
/bin:/usr/bin:/sbin:

將 PATH 變數取出,我要找出第一到第三,還有第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 1-3,5
/bin:/usr/bin:/sbin:/usr/local/bin

實用例子:只顯示/etc/passwd的使用者和shell
#cat /etc/passwd | cut -d ‘:‘ -f 1,7
root:/bin/bash
daemon:/bin/sh
bin:/bin/sh

截取指定個數的字元
$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2-5 ` // 截取第2到第5個字元
$ echo $a  
oot:

$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c -2 `   // 截取前兩個字元
$ echo $a  
ro

$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2- `    // 截取第2個以後的
$ echo $a  
oot:x:0:0:root:/root:/bin/bash

指定檔案,最後一個參數是檔案名稱
$ > cat cut_test.txt
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

$ > cut -d : -f 1,6 ./cut_test.txt
root:/root
bin:/bin
daemon:/sbin
adm:/var/adm

或者用cut -d : -f 1,6 cut_test.txt 和 cat cut_test.txt | cut -d : -f 1,6 都可以

shell -- cut用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.