在 Linux 中使用 cat 命令
cat
![](/data/attachment/album/202307/23/144250ljc3zwgjt7llznxj.jpg)



> 
> `cat` 命令的用途不仅仅是显示文件内容。
> 
> 
> 


`cat` 命令用于打印文本文件的文件内容。至少，大多数 Linux 用户都是这么做的，而且没有什么问题。


`cat` 实际上代表 “<ruby> 连接 <rt>  concatenate </rt></ruby>”，创建它是为了 [合并文本文件](https://linuxhandbook.com:443/merge-files/)。但只要有一个参数，它就会打印文件内容。因此，它是用户在终端中读取文件而无需任何其他选项的首选。


### 在 Linux 中使用 cat 命令


要使用 `cat` 命令，你必须遵循给定的命令语法：



```
cat [options] Filename(s)

```

这里：


* `[options]` 用于修改 `cat` 命令的默认行为，例如使用 `-n` 选项获取每行的数字。
* `Filename` 是你输入要使用的文件的文件名的位置。


为了简单起见，我将在本指南中使用名为 `Haruki.txt` 的文本文件，其中包含以下文本行：



```
Hear the Wind Sing (1979)
Pinball, 1973 (1980)
A Wild Sheep Chase (1982)
Hard-Boiled Wonderland and the End of the World (1985)
Norwegian Wood (1987)
Dance Dance Dance (1990)
South of the Border, West of the Sun (1992)
The Wind-Up Bird Chronicle (1994)
Sputnik Sweetheart (1999)
Kafka on the Shore (2002)
After Dark (2004)
1Q84 (2009-2010)
Colorless Tsukuru Tazaki and His Years of Pilgrimage (2013)
Men Without Women (2014)
Killing Commendatore (2017)

```

那么，在没有任何选项的情况下使用时，输出会是什么？ 好吧，让我们看一下：



```
cat Haruki.txt

```

![use cat command in Linux](/data/attachment/album/202307/23/144319gwxm9geewzmgljee.png)


正如你所看到的，它打印了整个文本文件！


但你可以做的远不止这些。让我向你展示一些实际例子。


#### 1、创建新文件


大多数 Linux 用户使用 `touch` 命令来 [创建新文件](https://itsfoss.com/create-files/)，但使用 `cat` 命令也可以完成相同的操作！


在这种场景下，`cat` 命令比 `touch` 命令有一个优势，因为你可以在创建文件时向文件添加文本。听起来很酷。不是吗？


为此，你需要使用 `cat` 命令，将文件名附加到 `>` 后面，如下所示：



```
cat > Filename

```

例如，在这里，我创建了一个名为 `NewFile.txt` 的文件：



```
cat > NewFile.txt

```

当你这样做了，就会有一个闪烁的光标要求你写一些东西，最后，你可以使用 `Ctrl + d` 来保存更改。


**如果你想创建一个空文件，则只需按 `Ctrl + d` 而不进行任何更改。**


![Using cat command](/data/attachment/album/202307/23/144320ch9z023h2u09h5s3.svg)


这就好了！现在，你可以使用 `ls` 命令来显示 [当前工作目录的内容](https://itsfoss.com/list-directory-content/)：


![use the ls command to list the contents of the current working directory](/data/attachment/album/202307/23/144320hy5jrl3zweldypy0.png)


#### 2、将文件内容复制到另一个文件


考虑一个场景，你要将 `FileA` 的文件内容重定向到 `FileB`。


当然，你可以复制和粘贴。但是如果有几百或几千行怎么办？


简单。你可以使用 `cat` 命令来重定向数据流。为此，你必须遵循给定的命令语法：



```
cat FileA > FileB

```


> 
> ? 如果使用上述语法重定向文件内容，它将删除 `FileB` 的文件内容，然后重定向 `FileA` 的文件内容。
> 
> 
> 


例如，我将使用两个文本文件 `FileA` 和 `FileB`，其中包含以下内容：


![check the file contents using the cat command](/data/attachment/album/202307/23/144320upm3vsf6gm3vw2s3.png)


现在，如果我使用从 `FileA` 到 `FileB` 的重定向，它将删除 `FileB` 的数据，然后重定向 `FileA` 的数据：



```
cat FileA > FileB

```

![redirect the file content using the cat command](/data/attachment/album/202307/23/144320w9ahxhru9lgrzvae.png)


同样，你可以对多个文件执行相同的操作：



```
cat FileA FileB > FileC

```

![redirect file content of multiple files using the cat command](/data/attachment/album/202307/23/144321p7radd7aizihexaa.png)


可以看到，上面的命令删除了 `FileC` 的数据，然后重定向了 `FileA` 和 `FileB` 的数据。


#### 3、将一个文件的内容附加到另一个文件


有时你想要将数据附加到现有数据，在这种情况下，你必须使用 `>>` 而不是单个 `>`：



```
cat FileA >> FileB

```

例如，在这里，我将把两个文件 `FileA` 和 `FileB` 重定向到 `FileC`：



```
cat FileA.txt FileB.txt >> FileC.txt

```

![redirect file content without overriding using the cat command](/data/attachment/album/202307/23/144321dt6w0im6jvj4z77o.png)


如你所见，它保留了 `FileC.txt` 的数据，并将数据附加在末尾。



> 
> ? 你可以使用 `>>` 向现有文件添加新行。使用 `cat >> filename` 并开始添加所需的文本，最后使用 `Ctrl+D` 保存更改。
> 
> 
> 


#### 4、显示行数


你可能会遇到这样的情况，你想查看行数，这可以使用 `-n` 选项来实现：



```
cat -n File

```

例如，在这里，我将 `-n` 选项与 `Haruki.txt` 一起使用：


![get the number of the lines in the cat command](/data/attachment/album/202307/23/144321lc0fsffcmkiuu0ai.png)


#### 5、删除空行


在文本文档中留下多个空白行？ `cat` 命令将为你修复它！


为此，你所要做的就是使用 `-s` 标志。


但使用 `-s` 标志有一个缺点。你仍然留有一行空白：


![remove blank lines with the cat command](/data/attachment/album/202307/23/144321nhgq81j184wqi5i5.png)


正如你所看到的，它有效，但结果接近预期。


那么如何删除所有空行呢？ 通过管道将其传递给 `grep` 命令：



```
cat File | grep -v '^$'

```

这里，`-v` 标志将根据指定的模式过滤掉结果，`'^$'` 是匹配空行的正则表达式。


以下是我在 `Haruki.txt` 上使用它时的结果：



```
cat Haruki.txt | grep -v '^$'

```

![remove all the blank lines in text files using the cat command piped with grep regular expression](/data/attachment/album/202307/23/144322eblzl0fzq48bs888.png)


当获得完美的输出，你可以将其重定向到文件以保存输出：



```
cat Haruki.txt | grep -v '^$' > File

```

![save output of cat command by redirection](/data/attachment/album/202307/23/144322iv8l75ms8p3pzm8j.png)


### 这就是你到目前为止所学到的


以下是我在本教程中解释的内容的快速摘要：




| 命令 | 描述 |
| --- | --- |
| `cat <Filename>` | 将文件内容打印到终端。 |
| `cat >File` | 创建一个新文件。 |
| `cat FileA > FileB` | `FileB` 的文件内容将被 `FileA` 覆盖。 |
| `cat FileA >> FileB` | `FileA` 的文件内容将附加到 `FileB` 的末尾。 |
| `cat -n File` | 显示行数，同时省略文件的文件内容。 |
| `cat File | more` | 将 `cat` 命令通过管道连接到 `more` 命令以处理大文件。请记住，它不能让你向上滚动！ |
| `cat File | less` | 将 `cat` 命令通过管道传输到 `less` 命令，这与上面类似，但它允许你双向滚动。 |
| `cat File | grep -v '^$'` | 从文件中删除所有空行。 |


### ?️ 练习时间


如果你学到了新东西，用不同的可能性来执行它是最好的记忆方式。


为此，你可以使用 `cat` 命令进行一些简单的练习。它们将是超级基本的，就像 `cat` 一样是[最基本的命令之一](https://learnubuntu.com:443/top-ubuntu-commands/)。


出于练习目的，你可以 [使用 GitHub 上的文本文件](https://github.com:443/itsfoss/text-files)。


* 如何使用 `cat` 命令创建空文件？
* 将 `cat` 命令生成的输出重定向到新文件 `IF.txt`
* 能否将三个或更多文件输入重定向到一个文件？ 如果是，该如何做？


*（题图：MJ/f06c9b9c-689e-4a67-abe9-0487e26bd34b）*




---


via: <https://itsfoss.com/cat-command/>


作者：[Sagar Sharma](https://itsfoss.com/author/sagar/) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


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


OK
![Warp Terminal](/assets/images/warp-terminal.webp)


![Warp Terminal](/assets/images/warp-terminal.webp)

The cat command is used to print the file contents of text files.

At least, that's what most Linux users use it for and there is nothing wrong with it.

Cat actually stands for 'concatenate' and was created to [merge text files](https://linuxhandbook.com/merge-files/). But withsingle argument, it prints the file contents. And for that reason, it is a go-to choice for users to read files in the terminal without any additional options.

## Using the cat command in Linux

To use the cat command, you'd have to follow the given command syntax:

`cat [options] Filename(s)`


Here,

`[options]`

are used to modify the default behavior of the cat command such as using the`-n`

option to get numbers for each line.`Filename`

is where you'll enter the filename of the file that you want to work with.

To make things easy, I will be using a text file named `Haruki.txt`

throughout this guide which contains the following text lines:

```
Hear the Wind Sing (1979)
Pinball, 1973 (1980)
A Wild Sheep Chase (1982)
Hard-Boiled Wonderland and the End of the World (1985)
Norwegian Wood (1987)
Dance Dance Dance (1990)
South of the Border, West of the Sun (1992)
The Wind-Up Bird Chronicle (1994)
Sputnik Sweetheart (1999)
Kafka on the Shore (2002)
After Dark (2004)
1Q84 (2009-2010)
Colorless Tsukuru Tazaki and His Years of Pilgrimage (2013)
Men Without Women (2014)
Killing Commendatore (2017)
```


So, what will be the output when used without any options? Well, let's have a look:

`cat Haruki.txt`


![use cat command in Linux](https://itsfoss.com/content/images/2023/06/use-cat-command-in-Linux.png)

As you can see, it printed the whole text file!

But you can do a lot more than just this. Let me show you some practical examples.

### 1. Create new files

Most Linux users use the touch command to [create new files](https://itsfoss.com/create-files/) but the same can be done using the cat command too!

The cat command has one advantage over the touch command in this case, as you can add text to the file while creating. Sounds cool. Isn't it?

To do so, you'd have to use the cat command by appending the filename to the `>`

as shown:

`cat > Filename`


For example, here, I created a file named `NewFile.txt`

:

`cat > NewFile.txt`


Once you do that, there'll be a blinking cursor asking you to write something and finally, you can use `Ctrl + d`

to save the changes.

**If you wish to create an empty file, then just press the Ctrl + d without making any changes.**

That's it! Now, you can use the ls command to show the [contents of the current working directory](https://itsfoss.com/list-directory-content/):

![use the ls command to list the contents of the current working directory](https://itsfoss.com/content/images/2023/06/use-the-ls-command-to-list-the-contents-of-the-current-working-directory.png)

### 2. Copy the file contents to a different file

Think of a scenario where you want to redirect the file content of **FileA** to the **FileB**

Sure, you can copy and paste. But what if there are hundreds or thousands of lines?

Simple. You use the cat command with the redirection of data flow. To do so, you'd have to follow the given command syntax:

`cat FileA > FileB`


If you use the above syntax to redirect file contents, it will erase the file contents of the FileB and then will redirect the file contents of the FileA.

For example, I will be using two text files FileA and FileB which contains the following:

![check the file contents using the cat command](https://itsfoss.com/content/images/2023/06/check-the-file-contents-using-the-cat-command.png)

And now, if I use the redirection from FileA to FileB, it will remove the data of FileB and then redirect the data of FileA:

`cat FileA > FileB`


![redirect the file content using the cat command](https://itsfoss.com/content/images/2023/06/redirect-the-file-content-using-the-cat-command.png)

Similarly, you can do the same with multiple files:

`cat FileA FileB > FileC`


![redirect file content of multiple files using the cat command](https://itsfoss.com/content/images/2023/06/redirect-file-content-of-multiple-files-using-the-cat-command.png)

As you can see, the above command removed the data of FileC and then redirected the data of FileA and FileB.

### Append the content of one file to another

There are times when you want to append data to the existing data and in that case, you'll have to use the `>>`

instead of single `>`

:

`cat FileA >> FileB`


For example, here, I will be redirecting two files `FileA`

and `FileB`

to the `FileC`

:

`cat FileA.txt FileB.txt >> FileC.txt`


![redirect file content without overriding using the cat command](https://itsfoss.com/content/images/2023/06/redirect-file-content-without-overriding-using-the-cat-command.png)

As you can see, it preserved the data of the `FileC.txt`

and the data was appended at the end of it.

You can use the `>>`

to add new lines to an existing file. Use `cat >> filename`

and start adding the text you want and finally save the changes with `Ctrl+D`

.

### 4. Show the numbers of line

You may encounter such scenarios where you want to see the number of lines, and that can be achieved using the `-n`

option:

`cat -n File`


For example, here, I used the `-n`

option with the `Haruki.txt`

:

![get the number of the lines in the cat command](https://itsfoss.com/content/images/2023/06/get-the-number-of-the-lines-in-the-cat-command.png)

### 5. Remove the blank lines

Left multiple blank lines in your text document? The cat command will fix it for you!

To do so, all you have to do is use the `-s`

flag.

But there's one downside of using the `-s`

flag. You're still left with one blank space:

![remove blank lines with the cat command](https://itsfoss.com/content/images/2023/06/remove-blank-lines-with-the-cat-command.png)

As you can see, it works but the results are close to the expectations.

So how would you remove all the empty lines? By piping it to the grep command:

`cat File | grep -v '^$'`


Here, the `-v`

flag will filter out the results as per `the `

specified pattern and `'^$'`

is a regular expression that matches the empty lines.

And here are the results when I used it over the `Haruki.txt`

:

`cat Haruki.txt | grep -v '^$'`


![remove all the blank lines in text files using the cat command piped with grep regular expression](https://itsfoss.com/content/images/2023/06/remove-all-the-blank-lines-in-text-files-using-the-cat-command-piped-with-grep-regular-expression.png)

Once you have the perfect output, you can redirect it to a file to save the output:

`cat Haruki.txt | grep -v '^$' > File`


![save output of cat command by redirection](https://itsfoss.com/content/images/2023/06/save-output-of-cat-command-by-redirection.png)

## That's what you've learned so far

Here's a quick summary of what I explained in this tutorial:

Command | Description |
---|---|

`cat <Filename>` |
Prints the file content to the terminal. |

`cat >File` |
Create a new file. |

`cat FileA > FileB` |
File contents of the `FileB` will be overridden by the `FileA` . |

`cat FileA >> FileB` |
File contents of the `FileA` will be appended at the end of the `FileB` . |

`cat -n File` |
Shows the number of lines while omitting the file contents of the File. |

`cat File | more` |
Piping the cat command to the more command to deal with large files. Remember, it won't let you scroll up! |

`cat File | less` |
Piping the cat command to the less command, which is similar to above, but it allows you to scroll both ways. |

`cat File | grep -v '^$'` |
Removes all the empty lines from the file. |


## 🏋️It's time to exercise

If you learned something new, executing it with different possibilities is the best way to remember.

And for that purpose, here are some simple exercises you can do with the cat command. They will be super basic as cat too is[ one of the most basic commands](https://learnubuntu.com/top-ubuntu-commands/).

For practice purposes, you can [use our text files from GitHub.](https://github.com/itsfoss/text-files)

- How would you create an empty file using the cat command?
- Redirect output produced by the cat command to a new file
`IF.txt`

- Can you redirect three or more file inputs to one file? If yes, then how?