四时宝库

程序员的知识宝库

Linux命令行之cut和grep命令(linux cut tab)

cut命令

cut命令输出文件中的一列或多列。第一种分割方法是使用分隔符,cut可以使用-f来指定取哪一列,默认是tab分隔符(可以使用-d指定分隔符),因为animals.txt正好是由tab分隔的,下面的命令打印每行的第二个字段,也就是书名:

$ cut -f2 animals.txt
Programming Python
SSH, The Secure Shell
Intermediate Perl
MySQL High Availability
Linux in a Nutshell
Cisco IOS in a Nutshell
Writing Word Macros

组合head命令只输出前三行:

$ cut -f2 animals.txt | head -n3
Programming Python
SSH, The Secure Shell
Intermediate Perl

剪切多个列可以使用逗号分隔列索引:

$ cut -f1,3 animals.txt | head -n3
python 2010
snail 2005
alpaca 2012

或按数字范围:

$ cut -f2-4 animals.txt | head -n3
Programming Python 2010 Lutz, Mark
SSH, The Secure Shell 2005 Barrett, Daniel
Intermediate Perl 2012 Schwartz, Randal

第二种切割方法是使用-c指定字符位置,输出文件每一行的前三个字符,可以用逗号(1,2,3)或范围(1-3):

$ cut -c1-3 animals.txt
pyt
sna
alp
rob
hor
don
ory

假如 animals.txt 文件有几千行,而我们只需要提取作者的名。先取第四个字段,作者姓名:

$ cut -f4 animals.txt
Lutz, Mark
Barrett, Daniel
Schwartz, Randal
?

然后使用 -d 再次 cut ,-d 指定分隔符为逗号,这样就可以取到作者的名:

$ cut -f4 animals.txt | cut -d, -f1
Lutz
Barrett
Schwartz
?

grep命令

grep 是一个非常强大的命令,用于输出符合匹配条件的行。以下命令输出 animals.txt中包含Nutshell的行:

$ grep Nutshell animals.txt
horse Linux in a Nutshell 2009 Siever, Ellen
donkey Cisco IOS in a Nutshell 2005 Boney, James

grep 还可以使用 -v 过滤匹配的行。下面命令输出的是不含Nutshell的行:

$ grep -v Nutshell animals.txt
python Programming Python 2010 Lutz, Mark
snail SSH, The Secure Shell 2005 Barrett, Daniel
alpaca Intermediate Perl 2012 Schwartz, Randal
robin MySQL High Availability 2014 Bell, Charles
oryx Writing Word Macros 1999 Roman, Steven

grep 对于在文件集合中查找文本很有用,比如在所有txt文件中查找包含Perl的行:

$ grep Perl *.txt
animals.txt:alpaca Intermediate Perl 2012 Schwartz, Randal
essay.txt:really love the Perl programming language, which is
essay.txt:languages such as Perl, Python, PHP, and Ruby

grep 读取 stdin 并写入 stdout,非常适合管道操作。假设想知道目录 / usr/lib 里有多少个子目录,没有单个 Linux 命令可以使用。先看 ls -l 命令的输出:

$ ls -l /usr/lib
drwxrwxr-x 12 root root 4096 Mar 1 2020 4kstogram
drwxr-xr-x 3 root root 4096 Nov 30 2020 GraphicsMagick-1.4
drwxr-xr-x 4 root root 4096 Mar 19 2020 NetworkManager
-rw-r--r-- 1 root root 35568 Dec 1 2017 attica_kde.so
-rwxr-xr-x 1 root root 684 May 5 2018 cnf-update-db
?

第一个字符为d表示这是一个目录,先使用 cut 隔离第一列:

$ ls -l /usr/lib | cut -c1
d
d
d
-
-
?

然后用 grep 只保留包含 d 的行:

$ ls -l /usr/lib | cut -c1 | grep d
d
d
d
?

最后用 wc 统计行数就可以得出结果:

$ ls -l /usr/lib | cut -c1 | grep d | wc -l
145

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接