Bash 工作代码从文件中删除第一行或最后一行

发布于 2024-12-17 13:06:56 字数 243 浏览 2 评论 0原文

我看到了 sed 示例,但无论我怎么写,它都不会删除我的第一行。实际上,我做了更多测试,它也不会删除我的第一行,所以可以肯定我做错了什么:

sed '1d' filename

或者对于最后一行,

sed '$d' file name

我希望更改发生在同一个文件中,并且不希望有另一个输出文件。 那么,删除文件中最后一行的正确方法是什么?

I saw the sed examples, but no matter how I write that it won't delete my first line. Actually, I did more tests and it won't delete my first line either, so for sure I'm doing something wrong:

sed '1d' filename

or for last line

sed '$d' file name

I want the changes to take place in the same file, and don't want another output file.
So please, what's the correct way to remove the last line in my file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

独孤求败 2024-12-24 13:06:56

sed -i '$d' 文件名-i 标志就地编辑文件。

sed -i '$ d' filename. The -i flag edits file in place.

九八野马 2024-12-24 13:06:56

干得好 !
删除第一行(也兼容 BSD/MacOS)

sed '1,1d' file1  >> file1.out

删除最后一行/行

sed '$d' file2  >> file2.out 

Here you go !
delete first line (also BSD/MacOS compatible)

sed '1,1d' file1  >> file1.out

delete last row/line

sed '$d' file2  >> file2.out 
十级心震 2024-12-24 13:06:56

如果您的 sed 支持就地编辑,则为 sed -e '1d' -e '$d' -i filename

If your sed supports in-place editing, it's sed -e '1d' -e '$d' -i filename.

最舍不得你 2024-12-24 13:06:56

您可以使用 --in-place (-i) 开关:

sed -i '$d' filename

来源:man sed

You can use the --in-place (-i) switch:

sed -i '$d' filename

Source: man sed

煮茶煮酒煮时光 2024-12-24 13:06:56

因为没有人给予它任何爱:

ed filename <<'END'
1d
$d
w
q
END

Because nobody gives it any love:

ed filename <<'END'
1d
$d
w
q
END
半葬歌 2024-12-24 13:06:56

由于 sed 未标记,所以给出这个答案。

head -`wc -l test2.cc | awk '{print ($1-1)}'` test2.cc

Giving this answer since sed is not tagged.

head -`wc -l test2.cc | awk '{print ($1-1)}'` test2.cc
攒一口袋星星 2024-12-24 13:06:56

尝试cat file1 | sed "1,1d; $d" >文件2

Try cat file1 | sed "1,1d; $d" > file2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文