unix 跳过头 bash 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9281449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:34:07  来源:igfitidea点击:

unix skip-header bash function

bash

提问by dfrankow

Somewhere on stackoverflow I got a bash function called "body" which would echo the header (first line) of a file, and pass the body (rest of the lines) along to stdout. This has been very useful for me to work with files that have headers.

在 stackoverflow 的某个地方,我得到了一个名为“body”的 bash 函数,它会回显文件的标题(第一行),并将正文(其余行)传递给标准输出。这对我处理带有标题的文件非常有用。

Example:

例子:

file.csv:

文件.csv:

field1,field2
a,2
b,1

Commands:

命令:

$ sort -k2,2 -nr file.csv -t,
a,2
b,1
field1,field2

$ cat file.csv | body sort -nr -t, -k2,2
field1,field2
a,2
b,1

Not a great example, but it shows the header staying on top.

不是一个很好的例子,但它显示标题保持在顶部。

Minutes of Googling and searching stackoverflow have revealed nothing.

谷歌搜索和搜索 stackoverflow 的几分钟没有透露任何信息。

Can anyone find or reconstruct such a function?

任何人都可以找到或重建这样的函数吗?

采纳答案by dfrankow

@summea found the answer I was seeking: the body function of Bash from here:

@summea 从这里找到了我正在寻找的答案:Bash 的身体功能:

# print the header (the first line of input)
# and then run the specified command on the body (the rest of the input)
# use it in a pipeline, e.g. ps | body grep somepattern
body() {
    IFS= read -r header
    printf '%s\n' "$header"
    "$@"
}

回答by summea

Here is one way that would allow you to grab the header... and then grab the rest of the csv file, and sort (or whatever else you want to do with the data,) and it all gets saved to the outpipe.

这是一种允许您获取标题的方法……然后获取 csv 文件的其余部分,并进行排序(或您想要对数据执行的任何其他操作),然后将其全部保存到 .csv 文件中outpipe

head -1 file.csv > outpipe | tail -n+2 file.csv | sort >> outpipe

Edit:

编辑:

If that approach doesn't work for you, you could always try something like the answers in this previous discussion.

如果这种方法对您不起作用,您可以随时尝试类似前面讨论中的答案的方法。

回答by user unknown

The basis would be just to reconstruct the out.file from file:

基础只是从文件重建 out.file :

(head -n1 file; tail -n+2 file) > out.file

You would operate somehow on the second part:

你会在第二部分以某种方式操作:

(head -n1 file; tail -n+2 file | voodoo -zack -peng) > out.file