sed:为什么不执行大括号后的命令?

时间:2013-07-04 16:41:26

标签: sed

$ cat thegeekstuff.txt

#Linux
        Administration
        Scripting
        Tips and Tricks

#Windows
        Administration

#Database
        Mysql
        Mysql
        Oracle
        Queries
        Mysql
        Procedures

$ sed -n '/Mysql/{g;1!p;};h' thegeekstuff.tx

#Database
#Database
        Queries

这意味着对于匹配模式的行不执行h命令。但我的印象是没有地址选择的命令适用于每一行。有人可以解释为什么它会像这样吗?

2 个答案:

答案 0 :(得分:3)

GNU代码:解释

sed -n '/Mysql/{g;1!p;};h'

h  # copy pattern space to hold space

/Mysql/{ # commands if the first pattern /Mysql/ is found
    g  # copy hold space to pattern space, in first /Mysql/ "#Database" is in hold space from the last line "h" command
    1!p # print the pattern space except in line #1, "#Database" is printed
 h # copy pattern space "#Database" to hold space

 /Mysql/{ # commands if the second pattern /Mysql/ is found
    g  # copy hold space to pattern space, in second /Mysql/ "#Database" is again in hold space from last "h" command
    1!p # print the pattern space except in line #1, "#Database" is printed again
  h # copy pattern space "#Database" to hold space

 /Mysql/{ # commands if the third pattern /Mysql/ is found
    g  # copy hold space to pattern space, in third /Mysql/ is "Queries" in hold space from last line "h" command
    1!p # print the pattern space except in line #1, "Query" is printed now
  h # copy pattern space to hold space
} end program

答案 1 :(得分:0)

什么不起作用?你的命令完全按照它所说的那样工作。

{..}适用于grouping

/Mysql/ - 这是您提供的regex。因此{..}中的命令只会在他们看到Mysql的行中运行。

相反,h将为每一行运行。 h正在复制模式空间以保留缓冲区。

当您的分组看到Mysql行时,他们会将保留空间中的内容复制到模式空间。查看Mysql之前的行。结果Database被打印出来。对于后续行同样的事情发生。 Database命令中的模式空间仍为g

最后,它打印queries,因为那是Mysql之前由h命令捕获到保留缓冲区并由分组语句打印回来的行。