2013-09-21 27 views
0

這裏文件的第一部分的文件:bash shell中顯示使用BSD頭

line1 
line2 
⋮ 
line10 
Total 
Update time 

我想有文件的第一部分,除了最後2行。

輸出應該是這樣的:

line1 
line2 
⋮ 
line10 

我怎麼能做到這一點使用BSD頭?或其他oneliner?

謝謝!

+3

看看[one-liner:打印除最後3之外的所有行?](http://stackoverflow.com/questions/18923097/one-liner-print-all-lines-except-the -last-3) – Birei

回答

2

使用awk,這將打印除最後兩行外的所有行。

awk '{a[j++]=$0}END{for(i=0;i<j-2;i++){print a[i]}}' filename 
+0

需要將i = 1更改爲i = 0。 (: – sbs

+0

@JohnnySun,哦,是的更新了。 – user1502952

1

喜歡的東西

head file.txt -n -2 

應該工作,只要你的head版本允許-2說法。我的GNU版本的頭部作品

 
$ head --version 
head (GNU coreutils) 5.97 
Copyright (C) 2006 Free Software Foundation, Inc. 
This is free software. You may redistribute copies of it under the terms of 
the GNU General Public License . 
There is NO WARRANTY, to the extent permitted by law. 

Written by David MacKenzie and Jim Meyering. 
+0

這就是我喜歡的,但是BSD頭沒有這個功能...... – sbs

0

這將讓該文件除了最後線

file.txt的 |頭 - $(表達式$(WC -l file.txt的 |切-C-8) - )

變化大膽部分進行修改。

2

另一個AWK選項:

cat <<file>> | awk -v len=$(wc -l <<file>> | awk '{print $1}') 'NR < len - 2 { print $0 }' 
1

這可能會爲你工作:

[根@ GC-RHEL6-64操場]#貓文件
一號線
2號線
3號線
4號線
line5
line6
line7
line8
line9
line10

[根@ GC-RHEL6-64操場]#head -`expr \`wc -l < file\` - 2` file
LINE1
LINE2
line3中
LINE4
LINE5
LINE6
line7
line8

+1

使用'$()'而不是反引號:'head - $(expr $(wc -l <​​file) - 2)file' –

+0

Thanks @glennjackman!更可讀:) – Technext

2

扭轉文件,刪除第一 2線,然後轉回:

tac file | sed 1,2d | tac 
2

這個概念不會使用太多的緩衝區,是有用的甚至非常大的文件或管道絡繹不絕。它應該比迄今提供的任何其他解決方案都要好。在開始打印線條之前,您也不必等到最後。

awk 'BEGIN{X = 2; getline; a[NR % X] = $0; getline; a[NR % X] = $0}{print a[NR % X]; a[NR % X] = $0}' 

NR也可以與自身重置爲0如果NR的限制是關注另一個櫃檯更換。此外,它將取決於awk的實現,它是如何清除自身並重新使用內存的每個N行輸入 ,但概念已經存在。

awk 'BEGIN{X = 2; for(i = 0; i < X; ++i)getline a[i]}{i %= X; print a[i]; a[i++] = $0}'