【问题标题】:How to delete and update the content in second file using shell如何使用 shell 删除和更新第二个文件中的内容
【发布时间】:2017-12-19 06:46:36
【问题描述】:

我有以下两个文件test.txttest1.txt. 我想将test.txt 的数据更新为test1.txtabc.com 下,但是,首先它必须删除现有数据,以便最终输出看起来比如输出文件部分下的test1.txt

test.txt

10.100.4.10
10.100.4.11
10.100.4.12

test1.txt

[abc.com]
10.100.44.10
10.100.44.11

[xyz.com]
10.100.55.10
10.100.55.11

[等..]

输出文件

test1.txt

[abc.com]
10.100.4.10
10.100.4.11
10.100.4.12

[xyz.com]
10.100.55.10
10.100.55.11

【问题讨论】:

  • 目标是您添加一些自己的代码(到您的问题中),以至少显示您为解决这个问题所做的研究工作。
  • 看看这个链接,它指向了正确的方向:unix.stackexchange.com/questions/32908/…

标签: bash shell sh


【解决方案1】:

如果您事先知道地址 abc.com 并且条目之间用空行分隔,则使用以下 sed 命令。第一个删除 abc.com 和第一个空行之间的行,第二个从 test1.txt 插入您想要的文本。

$ sed '/^\[abc\.com\]/,/^$/{/^\[abc\.com\]/!{/^$/!d}}' test.txt | sed '/^\[abc.com\]/r test1.txt'
[abc.com]
10.100.4.10
10.100.4.11
10.100.4.12

[xyz.com]
10.100.55.10
10.100.55.11

【讨论】:

  • 现在,如果我在命令下手动运行它的工作。但是,在脚本中,当我调用域名和文件时,它不起作用。 /bin/sed -i '/\babc.com/,/^$/{/^[0-9]/d};/\babc.com/r test.txt' /tmp/test1.txt 下面是调用 bash 脚本。我试图用值和它取正确的值来回显下面的命令。什么地方出了错。 /bin/sed -i '/\b$dmname/,/^$/{/^[0-9]/d};/\b"$dmname"/r $file' /tmp/test1.txt跨度>
  • 已解决。下面在 bash 脚本中使用 /bin/sed -i "/\b$dmname/,/^$/{/^[0-9]/d};/\b"$dmname"/r $file" /tmp/ test1.txt
  • 是的,如果你想要 bash 变量扩展,你必须使用双引号。我还看到您使用了不同的删除标准。如果您需要删除的所有行都以数字开头,那很好,但如果在数字之前有任何空格,它将被跳过
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 2012-05-16
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
相关资源
最近更新 更多