Bash-将标题添加到管道表命令 [英] Bash - Adding titles into to a piped table command
问题描述
我有一个简单的脚本,可以将students.txt文件的内容作为基本表输出到打印文件,然后显示出来.
I have a simple script to output the content of the file students.txt as a basic table to the print file, which is then displayed.
#!/bin/bash
cat students.txt | column -t -s',' | sort -u -k3 > print.txt
cat print.txt
输出如下:
Consoling ST DWC 0900
Scribing RA DWC 1000
Gloater AU DWC 1100
Crimp DI DWC 1200
,依此类推.但是,我还希望能够为每列添加标题,并使它们完美对齐,以及不进行排序.我尝试使用printf和echo,但是当通过管道将它们显示到命令中时,它们无法显示,并且无法通过在管道外部打印标题名称来正确对齐列.我正在寻找所需的输出看起来像这样:
and so on. However I also want to be able to add headings for each column and have them align perfectly, as well as not being sorted. I have tried to use printf and echo but when piped into the command they do not display and I cannot align the columns correctly by printing the heading names outside of the pipe. The desired output I am looking for would look like this:
Family Name Initials Interviewer Initials Interview Time
Consoling ST DWC 0900
Scribing RA DWC 1000
Gloater AU DWC 1100
Crimp DI DWC 1200
我怎么能做到这一点?
推荐答案
有一个内衬:
cat <(echo "Family Name,Initials,Interviewer Initials,Interview Time") <(sort -u -k3 -t ',' students.txt) | column -s ',' -t > print.txt
这利用了流程替代.运行<()
中的命令,其输出显示为文件名. cat
连接两个文件",其中包含echo
(用于标题)和sort
(用于对students.txt
进行排序)的输出.
This makes use of Process Substitution. The command inside <()
is run and it's output appears as a filename. cat
concatenates the two "files", that contain the outputs of echo
(for the headers) and sort
(to sort your students.txt
).
-
sort
与选项-t ','
一起运行,以指定,"作为分隔符. -
column
与选项-s ','
一起运行,以指定,"作为分隔符.
sort
is run with option-t ','
to specifiy "," as the delimiter.column
is run with option-s ','
to specify "," as the delimiter.
编辑(感谢@tripleee指出):
EDIT (thanks to @tripleee for pointing it out):
可以修改oneliner,这样就不需要 Process Substitution 和cat
:
The oneliner can be modified, such that Process Substitution and cat
isn't necessary:
{ echo "Family Name,Initials,Interviewer Initials,Interview Time"; sort -u -k3 -t ',' students.txt; } | column -s ',' -t > print.txt
echo
和sort
由{}
分组,并在当前shell上下文中执行.重定向(通向column
的管道)将应用于整个组.供参考:分组命令.
echo
and sort
are grouped by {}
and are executed in the current shell context. The redirection (pipe to column
) is applied to the entire group. For reference: Grouping Commands.
这篇关于Bash-将标题添加到管道表命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!