【问题标题】:sed - Replacing characters within a linesed - 替换一行中的字符
【发布时间】:2014-07-28 17:25:53
【问题描述】:

我在一些需要修改的文件中有一些 html 链接:

      <a href="www.blah.edu/hello world of friends" class="blue">Hello World</a>

假设上述链接位于 test.txt 中。

我一直在尝试找到一种单行符,它可以在 href 链接中用下划线替换空格。所以

      <a href="www.blah.edu/hello world of friends" class="blue">Hello World</a>

应该是

      <a href="www.blah.edu/hello_world_of_friends" class="blue">Hello World</a>

据我所知,使用 sed:

     sed '/href=['"'"'"][^"'"'"']*['"'"'"]*"/{s;\s;_;g}' test.txt

当然,这会产生:

     <a_href="www.blah.edu/hello_world"_class="blue">Hello_World</a>

我明白为什么会这样。 /regex/ 位将整行拉入模式空间,然后 s;;;在整行上执行,而不仅仅是我需要的位。

如何仅在 href=" 内用空格替换下划线?有没有比使用 sed 更好的方法来考虑这个问题?

【问题讨论】:

    标签: regex sed


    【解决方案1】:

    您可以使用 GNU Awk 或 Mawk:

    awk 'BEGIN { RS = "href=\""; ORS = ""; FS = OFS = "\"" } NR > 1 { gsub(/ /, "_", $1); print RS } 1' file
    

    输出:

      <a href="www.blah.edu/hello_world_of_friends" class="blue">Hello World</a>
    

    【讨论】:

    • @JakeVines 欢迎 :)
    【解决方案2】:

    为此我选择 perl:您可以将代码放入替换部分并对其进行评估。

    perl -pe 's{(?<=href=")(.+?)(?=")}{ (my $x = $1) =~ s/\s/_/g; $x }ge' <<END
    <a href="www.blah.edu/hello world of friends" class="blue">Hello World</a>
    END
    
    <a href="www.blah.edu/hello_world_of_friends" class="blue">Hello World</a>
    

    有一些解释:

    perl -pe '
        s{
            (?<=href=")  # starting where the preceding text is: href="
            (.+?)        # find a non-greedy sequence of chars until
            (?=")        # the closing quote is next.
        }{ 
            (my $x = $1) =~ s/\s/_/g;    # replace whitespace with underscore 
            $x                           # and replace with the new value
        }gex
    '
    

    【讨论】:

    • 这很有趣。我的perl知识非常有限。你刚刚给了我一个理由去深入研究它。谢谢!
    猜你喜欢
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2014-04-11
    • 2012-10-09
    • 1970-01-01
    • 2012-02-17
    相关资源
    最近更新 更多