假设您可以在<a 之后有一个或多个空格,并且在= 标志周围有零个或多个空格,那么以下应该可以工作:
$ cat in.txt
<a href="http://www.wowhead.com/?search=Superior Mana Oil">
<a href="http://www.wowhead.com/?search=Tabard of Brute Force">
<a href="http://www.wowhead.com/?search=Tabard of the Wyrmrest Accord">
<a href="http://www.wowhead.com/?search=Tattered Hexcloth Sack">
#
# The command to do the substitution
#
$ sed -e 's#<a[ \t][ \t]*href[ \t]*=[ \t]*".*search[ \t]*=[ \t]*\([^"]*\)">#&\1</a>#' in.txt
<a href="http://www.wowhead.com/?search=Superior Mana Oil">Superior Mana Oil</a>
<a href="http://www.wowhead.com/?search=Tabard of Brute Force">Tabard of Brute Force</a>
<a href="http://www.wowhead.com/?search=Tabard of the Wyrmrest Accord">Tabard of the Wyrmrest Accord</a>
<a href="http://www.wowhead.com/?search=Tattered Hexcloth Sack">Tattered Hexcloth Sack</a>
如果您确定没有多余的空格,则该模式将简化为:
s#<a href=".*search=\([^"]*\)">#&\1</a>#
在sed 中,s 后跟任何字符(在本例中为#)开始替换。要替换的模式直到相同字符的第二次出现。因此,在我们的第二个示例中,要替换的模式是:<a href=".*search=\([^"]*\)">。我用\([^"]*\) 表示任何非" 字符序列,并将其保存在反向引用\1 中(\(\) 对表示反向引用)。最后,由# 分隔的下一个标记是替换。 & in sed 代表“whatever match”,在这种情况下是整行,\1 只匹配链接文本。
这又是模式:
's#<a[ \t][ \t]*href[ \t]*=[ \t]*".*search[ \t]*=[ \t]*\([^"]*\)">#&\1</a>#'
及其解释:
' quote so as to avoid shell interpreting the characters
s substitute
# delimiter
<a[ \t][ \t]* <a followed by one or more whitespace
href[ \t][ \t]*=[ \t]* href followed by optional space, = followed by optional space
".*search[ \t]*=[ \t]* " followed by as many characters as needed, followed by
search, optional space, =, followed by optional space
\([^"]*\) a sequence of non-" characters, saved in \1
"> followed by ">
# delimiter, replacement pattern starts
&\1 the matched pattern, followed by backreference \1.
</a> end the </a> tag
# end delimiter
' end quote
如果您真的确定总会有search= 后跟您想要的文字,您可以这样做:
$ sed -e 's#.*search=\(.*\)">#&\1</a>#'
希望对您有所帮助。