如何编辑Unix文件以在2个特定模式匹配后插入几行

时间:2015-05-11 14:55:26

标签: awk sed

我有一个包含以下内容的文件。我想编辑文件,以便每当在文件中看到LTPGY模式然后在行“set t table new $ m table]”之后,插入一个内容为“FOUND”的新行。

输入文件如下: -

  set ra [ 1 22 3 ] LTPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]



  set ra [ 1 22 3 ] STPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]


  set ra [ 1 22 3 ] LTPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]



  set ra [ 1 22 3 ] STPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]

我希望输出如下: -

  set ra [ 1 22 3 ] LTPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  FOUND
  set a [  $t process_axis]
  set a [  $t voltage_axis]



  set ra [ 1 22 3 ] STPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]


  set ra [ 1 22 3 ] LTPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  FOUND
  set a [  $t process_axis]
  set a [  $t voltage_axis]



  set ra [ 1 22 3 ] STPGY
  set a 0
  set a1 1

  set t [ table new $m table]
  set a [  $t process_axis]
  set a [  $t voltage_axis]

2 个答案:

答案 0 :(得分:1)

与gawk合作,在其他问题上未经测试:

gawk '
    /set ra / {found = /LTPGY/}
    1;
    index($0, "set t [ table new $m table]") && found {print "FOUND"}
' file

答案 1 :(得分:1)

这可能适合你(GNU sed):

sed '/LTPGY/{:a;n;/set t \[ table new $m table\]/!ba;p;s/\S.*/FOUND/}' file

专注于LTPGY之后的行,并找到所需的字符串,然后打印它,然后使用所需的字符串FOUND替换除前导空格以外的所有字符串。

相关问题