Linux 如何使用bash从文本文件中删除前两行和后四行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10460919/
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-08-06 06:11:19  来源:igfitidea点击:

How to delete first two lines and last four lines from a text file with bash?

linuxbash

提问by rebca

I am trying to delete first two lines and last four lines from my text files. How can I do this with Bash?

我试图从我的文本文件中删除前两行和后四行。我怎样才能用 Bash 做到这一点?

采纳答案by Frédéric Hamidi

You can combine tailand head:

您可以组合tailhead

$ tail -n +3 file.txt | head -n -4 > file.txt.new && mv file.txt.new file.txt

回答by Debaditya

Head and Tail

首尾

cat input.txt | tail -n +3 | head -n -4

Sed Solution

解决方案

cat input.txt | sed '1,2d' | sed -n -e :a -e '1,4!{P;N;D;};N;ba'

回答by pizza

You can call the ex editor from the bash command line using the following sample. Note it uses a here documentto end the list of commands to ex.

您可以使用以下示例从 bash 命令行调用 ex 编辑器。请注意,它使用here 文档来结束 ex 的命令列表。

ex text.file << EOF
1,2d
$
-3,.d
x
EOF

回答by finferflu

This is the quickest way I found:

这是我找到的最快的方法:

sed -i 1,2d filename