UNIX 替换文件中的特定行

发布于 2024-10-05 16:51:46 字数 155 浏览 0 评论 0原文

我的文件大小约为 5.5GB。我想查看文件的特定行。假设行号为 100001,我想用我自己的文本替换该行。如何使用Unix命令来实现这个操作。我无法在编辑器中查看该文件。我打不开那是远程机器。

任何人都可以分享一些想法来查看该行并将其替换为其他文本吗?

谢谢 :)

I have file about 5.5GB of size. I want to view a particular line of the file. Lets say line number 100001 and I want to replace that line with my own texts. How to achieve this operation using Unix command. I can not view the file in editor. I can not be opened and that is a remote machine.

Can anyone share some idea to view that line and replacing it with some other texts?

Thanks :)

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

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

发布评论

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

评论(1

抠脚大汉 2024-10-12 16:51:46

如果您想就地修改该行并且替换数据与被替换的文本长度相同,您可以使用 dd 来(小心!)覆盖文件的一部分。

# getting the byte offsets of the start and length of the line
perl -ne '$s+=length; if ($.==100001) {print "$s + ",length,"\n"; exit}' bigfile

# writing over the existing data
echo 'new line' | dd of=bigfile bs=1 seek=$start count=$length conv=notrunc

如果替换数据的长度不同,并且它不在文件的最末尾,则您别无选择,只能重写文件。这需要有足够的磁盘空间来保存大文件及其副本!

# The old file is renamed to bigfile.bak; a new bigfile is written with changes.
sed -i.bak -e '100001 c \
new line' bigfile

If you want to modify the line in-place and the replacement data is the same length as the text being replaced, you can use dd to (carefully!) overwrite part of the file.

# getting the byte offsets of the start and length of the line
perl -ne '$s+=length; if ($.==100001) {print "$s + ",length,"\n"; exit}' bigfile

# writing over the existing data
echo 'new line' | dd of=bigfile bs=1 seek=$start count=$length conv=notrunc

If the replacement data is a different length, and it's not at the very end of the file, you have no choice but to rewrite the file. This requires having enough disk space to keep both bigfile and a copy of it!

# The old file is renamed to bigfile.bak; a new bigfile is written with changes.
sed -i.bak -e '100001 c \
new line' bigfile
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文