【问题标题】:Unix: Replace line with string in another fileUnix:用另一个文件中的字符串替换行
【发布时间】:2021-04-18 17:58:05
【问题描述】:

文件 1.txt

1.1.1.1

文件2.txt

tcp=ipv4
netmask=255.255.255.0
ip=

所需的输出:

tcp=ipv4
netmask=255.255.255.0
ip=1.1.1.1

我想用 "ip=" 字符串替换 File1.txt 值搜索中的 File2.txt 中的完整行。

我试试:

sed '/ip=/r File1.txt' File2.txt | sed '/ip=/d'

输出:

tcp=ipv4
netmask=255.255.255.0
1.1.1.1

如何添加 "ip=" 字符串值以获得所需的输出?

【问题讨论】:

  • 请向我们展示您最近尝试的代码以及您遇到的问题。另请参阅:How to Askhelp center
  • sed '/ip/r File1.txt' File2.txt
  • sed '/ip/r File1.txt' File2.txt | sed '/^ip=/{N; s/\n//}'?
  • sed: 1: "/^ip=/{N; s/\n//}": 替换命令中的错误标志:'}'
  • @DarvinRiveraAguilar,SO 不鼓励稍后更改问题,因此请将其恢复为您的实际问题,否则对于未来用户的所有给出的答案将毫无意义,谢谢。

标签: unix awk sed replace


【解决方案1】:
IP=`cat File1.txt`
sed "/^ip=$/s/$/$IP/" File2.txt

【讨论】:

    【解决方案2】:

    您能否尝试在 GNU awk 中使用所示示例进行跟踪、编写和测试。这也将处理 file1.txt 和 fil2.txt 中的多个出现/值。

    awk -F'=' '
    BEGIN{ FS=OFS="=" }
    FNR==NR{
      arr[++count]=$0
      next
    }
    /^ip/{
      print $1 OFS arr[++count1]
      next
    }
    1' file1.txt file2.txt
    

    说明:为上述添加详细说明。

    awk  '                      ##Starting awk program from here.
    BEGIN{ FS=OFS="=" }
    FNR==NR{                   ##Checking condition FNR==NR which will be TRUE when file1.txt is being read.
      arr[++count]=$0          ##Creating arr with index of increasing value of count and its value is current line.
      next                     ##next will skip all further statements from here.
    }
    /^ip/{                     ##Checking condition if line starts from ip then do following.
      print $1 OFS arr[++count1]   ##Printing current line and arr with index of increasing value of count1.
      next                     ##next will skip all further statements from here.
    }
    1                          ##1 will print all lines here.
    ' file1.txt file2.txt      ##Mentioning Input_file names here.
    

    【讨论】:

    • 如果我在 file2.txt 中有空格分隔会发生什么,例如:ip 8.8.8.8?
    • @DarvinRiveraAguilar,您需要将分隔符更改为 FS=OFS="\t" 干杯
    • with \t add File1.txt line at end ip 8.8.8.8 of File2.txt: ip 8.8.8.8 1.1.1.1 I need replace always last ip value in File2.txt
    • @DarvinRiveraAguilar,请将您的问题回复为您的实际问题,将ip file1_value 更改为ip file2_value-F'=' 更改为-F'\t' ,这样就可以解决问题了。
    猜你喜欢
    • 2019-03-21
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多