【问题标题】:Replace line with multiple trailing patterns用多个尾随模式替换行
【发布时间】:2013-08-26 00:24:08
【问题描述】:

我有 2 个名为 myfile.txtresponsefile.txt 的文件,如下所示。

myfile.txt

user=myname
Was_WAS_AdminId=CN=wsadmin,OU=service,OU=WAS_Secure,OU=tb,ou=dcdc,ou=sysadm,dc=info,dc=prd,dc=dcdc

responsefile.txt

'#'Please fill the user id details.
'#'Here is example user=urname.
user=
'#'Please fill the details.
'#'Here is example Was_WAS_AdminId=CN=wsadmin-xxxx.
Was_WAS_AdminId=

现在,使用上述两个文件希望在替换匹配模式后有以下最终结果。 responsefile.txt 内容应该是完整的,只是匹配的模式应该以 myfile.txt 中提供的详细信息为前缀,或者只替换整个匹配行,因为两个文件中的第一个模式相同并且将超过 100 个模式。所以,请提出一个简单的解决方案。

responsefile.txt(新文件替换/替换为模式)

'#'Please fill the user id details.
'#'Here is example user=urname.
user=myname
'#'Please fill the details.
'#'Here is example Was_WAS_AdminId=CN=wsadmin-xxxx.
Was_WAS_AdminId=CN=wsadmin,OU=service,OU=WAS_Secure,OU=tb,ou=dcdc,ou=sysadm,dc=info,dc=prd,dc=dcdc

两个文件中的模式相同,例如两个文件中的“user=”或“Was_WAS_AdminId=”。

【问题讨论】:

  • 试过 awk -F '=' 'FNR == NR

标签: linux bash sed awk


【解决方案1】:

这是一个 awk one 班轮:

$ awk -F= 'NR==FNR{a[$1]=$0;next}$1 in a{$0=a[$1]}1' myfile.txt responsefile.txt 
'#'Please fill the user id details.
'#'Here is example user=urname.
user=myname
'#'Please fill the details.
'#'Here is example Was_WAS_AdminId=CN=wsadmin-xxxx.
Was_WAS_AdminId=CN=wsadmin,OU=service,OU=WAS_Secure,OU=tb,ou=dcdc,ou=sysadm,dc=info,dc=prd,dc=dcdc

命令中两个文件的顺序很重要

【讨论】:

  • 嗨 sputnick,上面的文件没有在同一个文件中更新。
  • @user2692634 不,它没有。但是您可以通过awk ..... > tmp && mv tmp responsefile.txt 更新您的文件
【解决方案2】:

这个 awk 应该可以工作:

awk -F'=' 'FNR==NR{i=index($0, "="); a[substr($0, 1, i-1)]=substr($0, i+1);next} ($1 in a) {$0=$0 a[$1]}1' myfile.txt responsefile.txt

'#'Please fill the user id details.
'#'Here is example user=urname.
user=myname
'#'Please fill the details.
'#'Here is example Was_WAS_AdminId=CN=wsadmin-xxxx.
Was_WAS_AdminId=CN=wsadmin,OU=service,OU=WAS_Secure,OU=tb,ou=dcdc,ou=sysadm,dc=info,dc=prd,dc=dcdc

【讨论】:

  • 嗨 Anubhava,上述文件未在 responsefile.txt 的同一文件中更新。
猜你喜欢
  • 1970-01-01
  • 2022-09-26
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 2022-10-02
相关资源
最近更新 更多