2012-02-14 47 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