【问题标题】:sed script to read file1 and search and replace in file2sed 脚本读取 file1 并在 file2 中搜索和替换
【发布时间】:2016-02-20 20:44:43
【问题描述】:

我有两个不同的文件:

文件 1 包含:

idd = home_mine
password = my_password

文件 2 包含:

// some generic information
otherfields = generic 
idd = generic_id 
psk = generic_password 
last_fields = generic_last

我想将 file2 中的 'iid' 替换为 file1 中包含的 idd

我想用 file1 中包含的 password 替换 file2 中的 'psk'。 (我希望 file1 密码字段与 psk 不同)。

所以 file2 看起来像:

//some generic info
otherfields = generic 
iid = home_mine 
psk = my_password 
last_fields = generic_last

是否有可以执行此操作的 sed 脚本? 速度或效率不是问题。

谢谢。

【问题讨论】:

  • 我认为它是这样的,但我已经让它工作了:
  • 读行时;执行 sed "/idd/s/$/$line/g \c" file2 完成
  • 你的输出去哪儿了?我想你想在 OSX 上使用 sed -i '/idd/....' file2sed -i"" /idd/.../.../' file2 ,或者如果你使用的是旧的 unixen 系统,那么 sed '/idd/.../.../' file2 > file2.out && mv file2.out file2。我也看不出/g 在这种情况下有什么帮助。使用解决方案扩展您的评论作为答案,我们可以在其中复制/粘贴您的示例,您可以接受它以获得宝贵的声誉积分。我也会赞成它,因为它的价值。祝你好运。
  • 我有这个 sed 脚本工作,但它在一个文件中。我想要一个非技术人员可以轻松编辑的简单文件:
  • /bin/sed -i '/iid=/ c\ iid="home_mine"' ./file2, /bin/sed -i '/ psk=/ c\ password=my_passwork' ./文件2

标签: replace sed


【解决方案1】:

我会使用 awk:

awk -F '[[:blank:]]*=[[:blank:]]*' -v OFS=" = " '
    NR == FNR {my_val[$1] = $2; next} 
    $1 == "iid" {$2 = my_val["idd"]}       # is the key "idd" or "iid"?
    $1 == "psk" {$2 = my_val["password"]} 
    {print}
' file1 file2

复杂的-F 值会占用= 周围的空格以形成输入字段分隔符。输出字段分隔符在每一侧使用一个空格。

【讨论】:

  • 谢谢你。你能显示我会在文件中搜索“iid”和“psk”的位置吗?谢谢
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 2014-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 2014-06-08
  • 2021-11-27
  • 2019-01-09
相关资源
最近更新 更多