首页 > 解决方案 > 是否可以将头部输出通过管道传输到 sed?

问题描述

输入文件

hello how are u
some what doing fine
so 
thats all
huh
thats great
cool
gotcha im fine

我想删除最后 4 行而不重定向到另一个文件或说就地编辑。

我用过head -n -3 input.txt,但它只删除了最后两行。

还想了解是否可以将 head 的输出通过管道传输到 sed

喜欢head -n -3 input.txt | sed ...

是的,我通过 sed 的选项来删除最后 n 行,如下所示,但无法理解命令的细微差别,所以继续使用 head 命令的替代方法

sed -e :a -e '$d;N;2,5ba' -e 'P;D' file

标签: bashsed

解决方案


编辑:不创建临时文件解决方案:

awk -i inplace -v lines=$(wc -l < Input_file) 'FNR<=(lines-4)' Input_file

您能否尝试关注并让我知道这是否对您有帮助。

tac Input_file | tail -n +5 | tac  > temp_file && mv temp_file Input_file

解决方案 2:使用awk.

awk -v lines=$(wc -l < Input_file) 'FNR<=(lines-4)' Input_file > temp_file && mv temp_file Input_file

推荐阅读