2

$ 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 命令。但我的印象是,没有地址选择的命令适用于每一行。有人可以解释为什么它会这样吗?

4

2 回答 2

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
于 2013-07-04T17:01:49.000 回答
0

什么不工作?你的命令完全按照它被告知的那样工作。

{..}用于分组

/Mysql/- 这是regex您提供的。所以命令 in{..}只会在他们看到的那一行运行Mysql

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

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

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

于 2013-07-04T17:08:32.230 回答