从零开始学习Linux(四十一):Shell编程之cut命令
2021-01-02 本文已影响0人
通靈鹿小六
1、cut命令
grep命令的作用是提取行,cut命令是提取列。
命令格式:cut [选项] 文件名;
选项说明:
-f 列号:提取第几列;
-d 分隔符:按照指定分隔符分割列;
创建文件test_cut.txt,内容如下所示:

注意:文件中ID和Name之间不是空格,而是Tab键;
1.1、提取test_cut文件第二列Name
执行命令:
cut -f 2 test_cut.txt

1.2、使用逗号提取文件中的多列
例如提取test_cut.txt文件中的ID和Name,执行命令:
cut -f 1,2 test_cut.txt

1.3、指定提取分隔符
当cut命令没有指定分隔符的时候,默认使用的是Tab键作为分隔符。
当指定分隔符以后,使用指定的分隔符来提取数据列。
创建文件test_cut2.txt,内容如下图所示:

数据列之间不再使用Tab键作为分隔符,而是使用分号作为分隔符。
例如提取Name和Gender两列,执行命令:
cut -d ";" -f 2,3 test_cut2.txt

一般在使用cut命令的时候和管道符“|”连着使用。