shell 的cut 命令用法

来源:互联网 发布:小米盒子看网络电视吗 编辑:程序博客网 时间:2024/05/13 07:08

原帖地址 :  http://blog.csdn.net/arkblue/article/details/8507989


shell 的cut 命令用法

分类: Linux shell 393人阅读 评论(0) 收藏 举报

和awk差不多的功能

例1

[plain] view plaincopy
  1. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -d : -f 1,5`  
  2.   
  3. shuohailhl@shuohailhl-PC /cygdrive/d  
  4. $ echo $a  
  5. root:root  
上面的例子中,把 root:x:0:0:root:/root:/bin/bash 重定向到cut命令里,-d表示分隔符,这里使用冒号: 作为分隔符,-f 表示字段,选择了第1,和第5个字段,

例 2,只打印第一个字段field

[plain] view plaincopy
  1. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -d :  -f 1`  
  2.   
  3. shuohailhl@shuohailhl-PC /cygdrive/d  
  4. $ echo $a  
  5. root  
例 3,打印第一个字段以后的所有字段,包含第一个字段
[plain] view plaincopy
  1. shuohailhl@shuohailhl-PC /cygdrive/d  
  2. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -d : -f 1-`  
  3.   
  4. shuohailhl@shuohailhl-PC /cygdrive/d  
  5. $ echo $a  
  6. root:x:0:0:root:/root:/bin/bash  
  7.   
  8. shuohailhl@shuohailhl-PC /cygdrive/d  
  9. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -d : -f 3-`   // 打印第3个字段后的所有字段,包含第三个字段  
  10.   
  11. shuohailhl@shuohailhl-PC /cygdrive/d  
  12. $ echo $a  
  13. 0:0:root:/root:/bin/bash  
例4 ,截取第2到第4个字段

[plain] view plaincopy
  1. shuohailhl@shuohailhl-PC /cygdrive/d  
  2. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -d : -f 2-4`  
  3.   
  4. shuohailhl@shuohailhl-PC /cygdrive/d  
  5. $ echo $a  
  6. x:0:0  
例 5 截取指定个数的字符

[plain] view plaincopy
  1. shuohailhl@shuohailhl-PC /cygdrive/d  
  2. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2-5 ` // 截取第2到第5个字符  
  3.   
  4.   
  5. shuohailhl@shuohailhl-PC /cygdrive/d  
  6. $ echo $a  
  7. oot:  
  8.   
  9. shuohailhl@shuohailhl-PC /cygdrive/d  
  10. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2-7 `  // 截取第2到第7个字符  
  11.   
  12. shuohailhl@shuohailhl-PC /cygdrive/d  
  13. $ echo $a  
  14. oot:x:  
  15.   
  16. shuohailhl@shuohailhl-PC /cygdrive/d  
  17. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c -2 `   // 截取前两个字符  
  18.   
  19. shuohailhl@shuohailhl-PC /cygdrive/d  
  20. $ echo $a  
  21. ro  
  22.   
  23. shuohailhl@shuohailhl-PC /cygdrive/d  
  24. $ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2- `    // 截取第2个以后的  
  25.   
  26. shuohailhl@shuohailhl-PC /cygdrive/d  
  27. $ echo $a  
  28. oot:x:0:0:root:/root:/bin/bash  

例 6 指定文件,最后一个参数是文件名

[plain] view plaincopy
  1. $ cat pass.txt  
  2. root:x:0:0:root:/root:/bin/bash  
  3. bin:x:1:1:bin:/bin:/sbin/nologin  
  4. daemon:x:2:2:daemon:/sbin:/sbin/nologin  
  5. adm:x:3:4:adm:/var/adm:/sbin/nologin  
  6. shuohailhl@shuohailhl-PC /cygdrive/d  
  7. $ cut -d : -f 1-3 ./pass.txt  
  8. root:x:0  
  9. bin:x:1  
  10. daemon:x:2  
  11. adm:x:3