用多个尾随模式替换行

时间:2013-08-25 15:47:14

标签: linux bash sed awk

我有2个文件名为 myfile.txt & responsefile.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=”。

2 个答案:

答案 0 :(得分:2)

这是一个awk one liner:

$ 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

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

答案 1 :(得分: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
相关问题