2012-02-14 46 views
3

某处在stackoverflow我有一个名为“body”的bash函数,它会回显文件头(第一行),并将body(其余行)传递给stdout。这对于我处理包含头文件的文件非常有用。unix跳过标题bash函数

实施例:

FILE.CSV:

field1,field2 
a,2 
b,1 

命令:

$ 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 

不是一个很好的例子,但它显示了头停留在顶部。

几分钟的谷歌搜索和搜索stackoverflow没有透露。

任何人都可以找到或重建这样的功能?

+2

LOL。 “谷歌搜索的时间...”微波社会很多? :) – 2012-02-14 17:33:08

+1

什么是“文件头”?这意味着很多不同的事情取决于文件类型。也许你想要'head'程序,输出文件的第一行? – 2012-02-14 17:34:58

+1

你有链接的**在某处stackoverflow **? – anubhava 2012-02-14 17:41:38

回答

2

@summea找到我寻求答案: Bash的身体功能从here

# 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" 
    "[email protected]" 
} 
5

这里有一种方法可以让你抓住头......然后抓住csv文件的其余部分,并对数据进行排序(或者其他任何你想要处理的数据),并将其全部保存到outpipe

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

编辑:

如果方法不为你工作,你总是可以尝试像在this previous discussion的答案。

+0

谢谢,但我知道尾巴是如何工作的。 – dfrankow 2012-02-14 17:44:21

+0

你不允许使用“尾巴”吗? – summea 2012-02-14 17:44:45

+0

我试图澄清以上:我不只是需要尾巴。它将第一行和其余行分开,将其余行交给管道,将第一行和其余行集中在一起输出。 – dfrankow 2012-02-14 17:47:49

2

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

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

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

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

太棒了。我不知道你可以将这两个命令的输出分组。谢谢! – 2013-10-24 14:49:21