Linux专栏 新手命令教程(附实例)
在此页
- Linux 列命令
- Q1。如何使用列命令?
- Q2。如何列分隔的输出?
- Q3。有多个定界符的情况呢?
- Q4。列命令如何处理空行?
- 结论
有时,在 Linux 中使用命令行时,您可能希望以分栏格式显示文件的内容。您会很高兴知道 Linux 中有一个命令行实用程序可以让您执行此操作。工具名为 column,我们将使用一些易于理解的示例来讨论此命令的基础知识。
但在我们这样做之前,值得一提的是,这里的所有示例都已经在 Ubuntu 18.04 LTS 机器上进行了测试。
Linux 列命令
Linux 中的 column 命令可让您使用分栏列表。以下是它的语法:
column [-entx] [-c columns] [-s sep] [file ...]
工具手册页是如何定义它的:
The column utility formats its input into multiple columns. Rows are
filled before columns. Input is taken from file operands, or, by
default, from the standard input.
以下是一些 Q&A 风格的示例,它们可以让您更好地了解列命令的工作原理。
Q1。如何使用列命令?
基本用法非常简单。假设您有一个名为 test.txt 的文件,其中包含以下信息:
1
2
3
4
5
6
7
8
9
10
现在,要对该文件的内容进行分栏,请按以下方式使用 column 命令:
column test.txt
你会得到这样的输出:
1 2 3 4 5 6 7 8 9 10
Q2。如何列分隔的输出?
假设一个文件包含以下内容:
No.|Country|Yes/No
01|India|Y
02|US|Y
03|Australia|Y
04|China|N
05|Russia|Y
06|Japan|Y
07|Singapore|Y
08|South Korea|N
09|Finaland|Y
10|Ireland|Y
现在,按以下方式运行列命令:
column test.txt -t -s "|"
这是产生的输出:
No. Country Yes/No
01 India Y
02 US Y
03 Australia Y
04 China N
05 Russia Y
06 Japan Y
07 Singpaore Y
08 South Korea N
09 Finaland Y
10 Ireland Y
仅供参考,列命令手册页是如何解释 -t 和 -s 命令行选项的:
-s Specify a set of characters to be used to delimit columns for the
-t option.
-t Determine the number of columns the input contains and create a
table. Columns are delimited with whitespace, by default, or
with the characters supplied using the -s option. Useful for
pretty-printing displays.
Q3.有多个定界符的情况呢?
在前面的示例中,您看到原始内容包含管道 |作为分隔符。所以 column 命令使用这个定界符来产生柱状格式的输出。但是,如果某些条目中有两个管道怎么办。例如,请看这里的第一行:
No.||Country||Yes/No
01|India|Y
02|US|Y
03|Australia|Y
04|China|N
05|Russia|Y
06|Japan|Y
07|Singpaore|Y
08|South Korea|N
09|Finland|Y
10|Ireland|Y
默认情况下,column 命令将多个相邻的定界符合并为一个定界符。但是,如果需要,您可以使用 -n 命令行选项来禁用该行为。所以在那种情况下,列命令将变为:
column -n test.txt -t -s "|"
Q4.列命令如何处理空行?
默认情况下,列命令忽略空行。但是,如果需要,您可以使用 -e 命令行选项来抑制此行为。
例如,文件内容行如下:
No.|Country|Yes/No
01|India|Y
02|US|Y
03|Australia|Y
04|China|N
05|Russia|Y
06|Japan|Y
07|Singapore|Y
08|South Korea|N
09|Finland|Y
10|Ireland|Y
会出来像:
No. Country Yes/No
01 India Y
02 US Y
03 Australia Y
04 China N
05 Russia Y
06 Japan Y
07 Singapore Y
08 South Korea N
09 Finland Y
10 Ireland Y
使用以下命令:
column -e test.txt -t -s "|"
结论
根据您在 Linux 命令行上执行的工作类型,column 命令可能对您有很大帮助。在本教程中,我们讨论了该工具提供的大多数选项。有关更多信息,请访问其手册页。