从文件中删除第一行或最后一行的 Bash 工作代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8234711/
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
Bash working code to delete first or last line from file
提问by k-man
I saw the sedexamples, but no matter how I write that it won't delete my first line. Actually, I did more tests and it won't delete my first line either, so for sure I'm doing something wrong:
我看到了sed例子,但无论我怎么写,它都不会删除我的第一行。实际上,我做了更多的测试,它也不会删除我的第一行,所以我肯定做错了什么:
sed '1d' filename
or for last line
或最后一行
sed '$d' file name
I want the changes to take place in the same file, and don't want another output file. So please, what's the correct way to remove the last line in my file?
我希望更改发生在同一个文件中,并且不想要另一个输出文件。那么请问,删除文件中最后一行的正确方法是什么?
回答by Russell Dias
sed -i '$ d' filename. The -iflag edits file in place.
sed -i '$ d' filename. 该-i标志在编辑文件到位。
回答by Rakesh
Here you go ! delete first line (also BSD/MacOS compatible)
干得好 !删除第一行(也兼容 BSD/MacOS)
sed '1,1d' file1 >> file1.out
delete last row/line
删除最后一行/行
sed '$d' file2 >> file2.out
回答by Mark Byers
回答by Michael Krelin - hacker
If your sed supports in-place editing, it's sed -e '1d' -e '$d' -i filename.
如果您的 sed 支持就地编辑,则它是sed -e '1d' -e '$d' -i filename.
回答by glenn Hymanman
Because nobody gives it any love:
因为没有人给它任何爱:
ed filename <<'END'
1d
$d
w
q
END
回答by Vijay
Giving this answer since sedis not tagged.
给出这个答案,因为sed没有标记。
head -`wc -l test2.cc | awk '{print (-1)}'` test2.cc
回答by luis.espinal
Try cat file1 | sed "1,1d; $d" > file2
尝试cat file1 | sed "1,1d; $d" > file2

