我们经常会遇到需要取出分字段的文件的某些特定字段,例如 /etc/password就是通过":"分隔各个字段的。可以通过cut命令来实现。例如,我们希望将系统账号名保存到特定的文件,就可以:
cut -d: -f 1 /etc/passwd > /tmp/users
-d用来定义分隔符,默认为tab键,-f表示需要取得哪个字段
当然也可以通过cut取得文件中每行中特定的几个字符,例如:
cut -c3-5 /etc/passwd
就是输出/etc/passwd文件中每行的第三到第五个字符。
-c 和 -f 参数可以跟以下子参数:
N 第N个字符或字段
N- 从第一个字符或字段到文件结束
N-M 从第N个到第M个字符或字段
-M 从第一个到第N个字符或字段
Consider a slight variation on the company.data file we've been playing with in this section:
406378:Sales:Itorre:Jan
031762:Marketing:Nasium:Jim
636496:Research:Ancholie:Mel
396082:Sales:Jucacion:Ed
If you want to print just columns 1 to 6 of each line (the employee serial numbers), use the -c1-6 flag, as in this command:
cut -c1-6 company.data
406378
031762
636496
396082
If you want to print just columns 4 and 8 of each line (the first letter of the department and the fourth digit of the serial number), use the -c4,8 flag, as in this command:
cut -c4,8 company.data
3S
7M
4R
0S
And since this file obviously has fields delimited by colons, we can pick out just the last names by specifying the -d: and -f3 flags, like this:
cut -d: -f4,3 company.data
Itorre
Nasium
Ancholie
Jucacion
Here is a summary of the most common flags for the cut command:
-c [n | n,m | n-m] Specify a single column, multiple columns (separated by a comma), or range of columns (separated by a dash).
-f [n | n,m | n-m] Specify a single field, multiple fields (separated by a comma), or range of fields (separated by a dash).
-dc Specify the field delimiter.
-s Suppress (don't print) lines not containing the delimiter.
shell>> cat example
test2
this is test1
shell>> cut -c0-6 example ## print 开头算起前 6 个字元
test2
this i
cut其实很有用
-c m-n 表示显示每一行的第m个字元到第n个字元。例如:
---------file-----------
liubi 23 14000
---------file-----------
# cut -c 3-9,12-20 file
liubi 14000
-f m-n 表示显示第m栏到第n栏(使用tab分隔)。例如:
---------file-----------
liubi 23 14000
---------file-----------
# cut -f 1,3 file
liubi 14000
| 发表你的评论在300字符内: (一个汉字等于两个字符) | |
|
问道网友
|
|