awk / Sed在特定字符串后替换单词

时间:2014-03-20 12:20:58

标签: unix sed awk

我有一个如下文件

<DATABASE name="ABC" url="jdbc:sybase:Tds:eqprod3:5060/ABC01" driver="com.sybase.jdbc2.jdbc.SybDriver" user="user" pwd="password" minConnections="10" maxConnections="10" maxConnectionLife="1440000" startDate="01/01/2014" endDate="01/30/2014" type="dev"/>

<DATABASE name="XYZ" url="jdbc:sybase:Tds:eqprod2:5050/XYZ01" driver="com.sybase.jdbc2.jdbc.SybDriver" user="user" pwd="password" minConnections="10" maxConnections="10" maxConnectionLife="1440000" startDate="02/01/2014" endDate="02/02/2014" type="dev"/>

现在,我想在网址部分中搜索单词ABC01,然后搜索startDate,然后更改该值,让我们说02/01/2014

你能不能帮助我获得所需的输出。

2 个答案:

答案 0 :(得分:1)

使用sed

sed '/ABC01/ s/startDate="[^"]*"/startDate="02\/01\/2014"/g' your.file

答案 1 :(得分:0)

此脚本适用于单行和多行DATABASE元素。

awk '
# search for ABC01 in url attribute
/url="[^"]*ABC01[^"]*"/{
  # set the flag
  f = 1;
  # current line number
  i1 = NR;
}
# save line if the flag is set
(f){lines[NR] = $0}
# output line otherwise
(!f){print $0}
# if the flag is set, search for startDate attribute
(f && $0 ~ /startDate="/){
  # replace value of startDate attribute with 02/01/2014
  s = gensub(/(startDate=")[^"]+/, "\\102/01/2014", 1, $0)
  # current line number
  i2 = NR;
  # output non-modified lines (no output if i2 == i1)
  for (i = i1; i < i2; i++){print lines[i]};
  # output modified line
  print s;
  # unset the flag
  f = 0;
}'