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

a
b
c

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

a
b

当前回答

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

这段代码可以达到目的。

其他回答

红宝石(1.9+)

ruby -ne 'BEGIN{prv=""};print prv ; prv=$_;' file

在macOS上,head -n -1不起作用,但你可以使用这个命令:

cat file.txt | tail -r | tail -n +2 | tail -r

Tail -r将其输入中的行顺序颠倒 Tail -n +2输出输入中从第二行开始的所有行

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

使用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}
awk 'NR>1{print buf}{buf = $0}'

本质上,这段代码表示:

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

对于每一行,重置缓冲区

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

删除zshrc文件中的最后一行,例如:

cat ~/.zshrc
sed -i '' -e '$ d' ~/.zshrc
cat ~/.zshrc