从特定扩展名的所有文件中删除最后一行

Remove last line from all files of a specific extension

我在一个目录中有几个具有相同扩展名 .txt 的文件。我想从所有 .txt 文件中删除最后一行。

我做的是

find . -type f -name '*.txt' -exec sed '$d' {} \;

这会为每个 .txt 文件从 sed 向终端打印所需的输出。

我要的是修改各自的文件

你应该在 sed 语句中使用 -i

要修改文件并进行一些更改,我们需要在 sed 命令中指定 -i

你的命令应该像

find . -type f -name '*.txt' -exec sed -i '$d' {} \;

但请注意,它将使用 .txt 更新所有文件,您将无法还原,因此请备份重要文件

试试这个:--

sed  -i '$d' *.txt

“$”用作行号,表示文件中的最后一行。

"d" 用于删除相应的行(在本例中为最后一行)。

“*.txt”用于select当前目录下所有扩展名为.txt的文件。

考虑到使用sed修改大量文件时丢失数据的风险,这是我在创建新子目录后使用的:

awk 'NR>1 {print last > "./modified/"FILENAME} {last=[=10=]}' *.txt

这会将扩展名为 .txt 的所有文件过滤到新文件中,并更改名为 modified.[=12 的子目录=]

参考:what is the easiest way to remove 1st and last line from file with awk?