我有一个文件,foo.txt,包含以下行:

a
b
c

我想要一个简单的命令,导致foo.txt的内容为:

a
b

当前回答

awk "NR != `wc -l < text.file`" text.file &> newtext.file

这段代码可以达到目的。

其他回答

awk 'NR>1{print buf}{buf = $0}'

本质上,这段代码表示:

对于第一行之后的每一行,打印缓冲行

对于每一行,重置缓冲区

缓冲区延迟了一行,因此最终打印的是第1行到第n-1行

Linux

$表示最后一行,d表示删除:

sed '$d' ~/path/to/your/file/name

操作系统

相当于sed -i:

sed -i '' -e '$ d' ~/path/to/your/file/name
awk "NR != `wc -l < text.file`" text.file &> newtext.file

这段代码可以达到目的。

你也可以试试这个方法:删除最后n行数的例子。

= 0;While [$a -lt 4];do sed -i '$ d' output.txt;A =expr $ A + 1;完成

删除文件(output.txt)的最后4行。

这两个解都是另一种形式。我发现下面这些更实际、更清晰、更有用:

使用dd:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
dd if=${ORIGINALFILE} of=${ORIGINALFILE}.tmp status=none bs=1 count=$(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc )
/bin/mv -f ${ORIGINALFILE}.tmp ${ORIGINALFILE}

使用截断:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
truncate -s $(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc ) ${ORIGINALFILE}