命令行技巧：分割文件内容
cut
![](/data/attachment/album/201905/03/162149iwhwrrgfrpaowrwp.jpg)


Fedora 发行版是一个功能齐全的操作系统，有出色的图形化桌面环境。用户可以很容易地通过单击动作来完成任何典型任务。所有这些美妙的易用性掩盖了其底层强大的命令行细节。本文是向你展示一些常见命令行实用程序的系列文章的一部分。让我们进入 shell 来看看 `cut`。


通常，当你在命令行中工作时，你处理的是文本文件。有时这些文件可能很长，虽然可以完整地阅读它们，但是可能会耗费大量时间，并且容易出错。在本文中，你将学习如何从文本文件中提取内容，并从中获取你所需的信息。


重要的是要意识到，在 Fedora 中有许多方法可以完成类似的命令行任务。例如，Fedora 仓库含有用于解析和处理文本的完整语言系统。此外，还有多个命令行实用程序可用于 shell 中任何可能的用途。本文只关注使用其中几个实用程序选项，从文件中提取一些信息并以可读的格式呈现。


### cut 使用


为了演示这个例子，在系统上使用一个标准的大文件，如 `/etc/passwd`。正如本系列的前一篇文章所示，你可以执行 `cat` 命令来查看整个文件：



```
$ cat /etc/passwd
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
...
```

此文件包含系统上所有所有账户的信息。它有一个特定的格式：



```
name:password:user-id:group-id:comment:home-directory:shell
```

假设你只想要系统上所有账户名的列表，如果你只能从每一行中删除 “name” 值。这就是 `cut` 命令派上用场的地方！它一次处理一行输入，并提取该行的特定部分。


`cut` 命令提供了以不同方式选择一行的部分的选项，在本示例中需要两个，`-d` 和 `-f`。`-d` 选项允许你声明用于分隔行中值的分隔符。在本例中，冒号（`:`）用于分隔值。`-f` 选项允许你选择要提取哪些字段值。因此，在本例中，输入的命令是：



```
$ cut -d: -f1 /etc/passwd
root
bin
daemon
adm
...
```

太棒了，成功了！但是你将输出打印到标准输出，在终端会话中意味着它需要占据屏幕。如果你需要稍后完成另一项任务所需的信息，这该怎么办？如果有办法将 `cut` 命令的输出保存到文本文件中，那就太好了。对于这样的任务，shell 有一个简单的内置功能，重定向功能（`>`）。



```
$ cut -d: -f1 /etc/passwd > names.txt
```

这会将 `cut` 的输出放到一个名为 `names.txt` 的文件中，你可以使用 `cat` 来查看它的内容:



```
$ cat names.txt
root
bin
daemon
adm
...
```

使用两个命令和一个 shell 功能，可以很容易地使用 `cat` 从一个文件进行识别、提取和重定向一些信息，并将其保存到另一个文件以供以后使用。




---


via: <https://fedoramagazine.org/command-line-quick-tips-cutting-content-out-of-files/>


作者：[Stephen Snow](https://fedoramagazine.org/author/jakfrost/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[MjSeven](https://github.com/MjSeven) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
The Fedora distribution is a full featured operating system with an excellent graphical desktop environment. A user can point and click their way through just about any typical task easily. All of this wonderful ease of use masks the details of a powerful command line under the hood. This article is part of a series that shows you some common command line utilities. So let’s drop into the shell, and have a look at **cut**.

Often when you work in the command line, you are working with text files. Sometimes these files may be quite long. Reading them in their entirety, while feasible, can be time consuming and prone to errors. In this installment you’ll learn how to extract content from text files, and get the information you want from them.

It’s important to recognize that there are many ways to accomplish similar command line tasks in Fedora. The Fedora repositories include entire language systems for parsing and working with text, as an example. Also, there are multiple command line utilities available for just about any purpose conceivable in the shell. This article will only focus on using a few of those utility choices, to extract some information from a file and present it in a readable format.

## Making the cut

To illustrate this example use a standard sizable file on the system like */etc/passwd*. As seen in a prior article in this series, you can execute the *cat* command to view an entire file:

$cat /etc/passwdroot: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 ...

This file contains information on all accounts present on the system. It has a specific format:

name:password:user-id:group-id:comment:home-directory:shell

Imagine that you want to simply have a list of all the account names on the system. If you could only cut out the *name* value from each line. This is where the *cut* command comes in handy! This command treats any input one line at a time, and extracts a specific part of the line.

The *cut* command provides options for selecting parts of a line differently, and in this example two of them are needed, *-d* which is an option to specify a delimiter type to use, and *-f* which is an option to specify which field of the line to cut. The *-d* option lets you declare the *delimiter* that separates values in a line. In this case a colon (:) is used to separate values. The *-f* option lets you choose which field value or values to extract. So for this example the command entered would be:

$cut -d: -f1 /etc/passwd

root

bin

daemon

adm

...

That’s great, it worked! But you get the printout to the standard output, which in a terminal session at least means the screen. What if you needed the information for another task to be done later? It would be really nice if there was a way to put the output of the *cut* command into a text file to save it. There is an easy builtin shell function for such a task, the redirect function (*>*).

$cut -d: -f1 /etc/passwd > names.txt

This will place the output of cut into a file called *names.txt* and you can check the contents with *cat:*

$cat names.txt

root

bin

daemon

adm

...

With two commands and one shell function, it was easy to identify using *cat*, extract using *cut*, and redirect the extracted information from one file, saving it to another file for later use.

*Photo by **Joel Mbugua** on **Unsplash**.*

## Mark

Cut is great for what it does. You will quickly run into situations with multiple delimiters and inconsistent lengths that awk is better suited to handle.

## Stephen Snow

Yeah, I was going to talk a bit about awk and gawk since they are much better at parsing more complex files, but the idea (which was started by Paul Frields) is a series of articles about useful command line tools. So I would suspect awk and gawk to appear in one at some point.

## John

Looking forward to the awk series

## Leslie Satenstein

I generally do cut -d: f1 /etc/passwd | sort > names.txt

Because I like my list in alphabetical order.

## Stephen Snow

That is the beauty of the command line tools available on a Linux system normally OOTB. They are flexible and combined with piping, redirects and other tools offer capabilities that super-cede their stand alone do one thing and do it well.

## Stuart D Gathman

I remember an SQL implementation a while back that compiled queries to shell scripts that did grep, cut, join, sort. The data was in plain text files. It was faster than database implementations for up to 1000s of records. Obviously, it is not going to scale – but so many applications are within the golden range for plain text files.

## Mark Senn

You may want to write about Perl (I especially recommend Perl 6) instead of awk,

or at least mention Perl in your awk article.

## rapra

Nice article. I have used ‘cut’ for years, but learnt awk a couple of years ago and was blown away by its awesome power.