使用 sed 和 perl 进行文字处理,将行从一个文件复制到另一个文件

发布于 2025-01-04 18:21:04 字数 305 浏览 6 评论 0原文

我是 Linux 新手,面临一项具有挑战性的任务。

我有 3 个数据文件,需要执行以下操作:

  1. 转到文件 1 的第 31 行,将其删除
  2. 从文件 2 中读取 1 行并添加代替已删除的行
  3. 转到文件 1 的第 97 行删除它,然后读取该行文件 2 中的 1 并添加到文件 1 中删除的行的位置。

保留相同的文件(即文件)也很重要,不能更改。

我尝试了不同版本的 sed 和 perl,以及缓冲区复制技巧,但没有成功。

我对所有建议持开放态度,并请求专家给我建议。

I am new to Linux and have a challenging task.

I have 3 data files, and need to do the following:

  1. Go to line 31 of file 1, delete it
  2. Read 1 line from file 2 and add in place of deleted line
  3. Go to line 97 of file 1 delete it and then read the line 1 from file 2 and add in place of that deleted line in file 1.

The thing is also important to keep the same file i.e file , it is not to be changed.

I tried different versions of sed and perl, with buffer copying tricks but was not successful.

I am open for all suggestions and request the experts to give me suggestions.

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

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

发布评论

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

评论(1

囍孤女 2025-01-11 18:21:04

我在您的问题中找不到对第三个文件的引用,但如果您的意思是用文件 2 的第一行替换文件 1 的行号 31,并将文件 1 的行号 97 替换为文件 2 的第二行

sed -i -e '30R f2
31d;96R f2
97d' f1

: f2 之后的行很重要,因此 sed 知道它是文件名的结尾。

请注意,R 命令是 GNU 扩展,它不是标准的。

I cannot find a reference to the 3rd file in your question, but if you mean replace line number 31 of file 1 with the 1st line of file 2, and replace line number 97 of file 1 with the 2nd line of file 2:

sed -i -e '30R f2
31d;96R f2
97d' f1

The new lines are important after f2 so sed knows that it is the end of the file name.

Note that the R command is a GNU extension, it is not standard.

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