在Linux中连接文件
1. 简介
有时,我们需要做一些需要同时使用多个文件的操作。这可能与在多个文件中搜索某些文本或将多个文件合并到一个新文件中一样常见。
在这个快速教程中,我们将展示一些有用的操作,这些操作可以让我们在 Linux 中连接文件时更轻松。
2. cat命令
在 Linux 中连接文件最常用的命令可能是cat ,它的名字来自concatenate。
命令语法遵循以下形式:
cat [options] [files]
在接下来的部分中,我们将深入研究该命令和我们可以使用的选项。
3. 显示文件
让我们先快速了解一下cat命令的基础知识。我们可以做的最直接的操作是显示一个文件:
cat myfile
这会在标准输出中显示myfile :
This is a text file.
4. 创建文件
我们也可以在没有文本编辑器的情况下使用cat创建新文件。
就像使用重定向运算符一样简单:
cat > newfile
之后,我们可以开始输入我们想要添加到文件中的内容:
creating a new file.
当我们要保存文件时,我们必须按CTRL+D。请注意,如果文件存在,它将被覆盖。
5. 连接文件
顾名思义,cat命令最常见的功能之一是连接文件。
最简单的串联是在标准输出中显示多个文件:
cat file1 file2
上面的命令按顺序显示文件:
My file 1
My file 2
我们还可以使用通配符来显示所有匹配通用模式的文件:
cat file*
到目前为止,我们一直在标准输出中显示文件,但我们可以将输出写入一个新文件:
cat file1 file2 > file3
此外,我们可以将文件附加到现有文件:
cat file1 >> file2
另一个有用的选项是从标准输入中读取,我们使用 - 表示:
cat - file1 > file2
然后,我们可以在file1之前输入我们想要连接的文本:
text from standard input
现在,如果我们键入cat file2来显示文件,我们可以看到我们引入的文本与file1连接:
text from standard input
My file 1
此外,我们可以在文件之后而不是之前附加标准输入:
cat file1 - > file2
如果我们走得更远一点,我们还可以将任何其他命令的输出连接到cat:
ls -la | cat > file1
最后,我们可以将cat输出通过管道传输到其他实用程序以创建更强大的命令:
cat file1 file2 file3 | sort > file4
在这种情况下,我们连接了三个文件,对连接的结果进行了排序,并将排序后的输出写入一个名为file4的新文件。
6. 其他选项
在cat命令的帮助下,我们可以找到一些可以添加到命令中的其他有用选项:
cat --help
Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s) to standard output.
With no FILE, or when FILE is -, read standard input.
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonempty output lines, overrides -n
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-u (ignored)
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
--help display this help and exit
--version output version information and exit
例如,我们可以使用*-n*选项:
cat -n myfile
显示每行的编号:
1 This is a test file.
2 It contains multiple lines.
或者,我们可以使用*-e*:
cat -e myfile
在这种情况下,它会在每行的末尾显示一个*$* :
This is a test file.$
It contains multiple lines.$
这些只是展示如何使用这些选项的一些简单示例。