2012-02-16 71 views
1

我正在开发一个bash补丁程序,以在纯文本文件上执行多项操作,以帮助减少多个Web服务器上的手动编辑。超出我的sed知识范围的一部分是我将如何去编辑一个不止一次出现的字符串,只编辑其中一个特定事件。看看下面的编校HTML例如:使用sed将字符串追加到模式的第四次出现

<div class="dashlet"> 
    <div class="body"> 
    <div class="detail-list-item"> 
     <!-- some content here --> 
    </div> 
    <div class="detail-list-item"> 
     <!-- some more content here --> 
    </div> 
    <div class="detail-list-item"> 
     <!-- some more content here --> 
    </div> 
    <div class="detail-list-item"> 
     <!-- some more content here --> 
    </div> 
    <div class="detail-list-item last-item"> 
     <!-- some final content here --> 
    </div> 
    </div> 
</div> 

我需要摆脱的代码的最后一块的,同时考虑到该文件可能会在将来的更新改变不理想,我使用下面的命令来删除由线

sed -i '29,33d' /path/to/file 

凡29是行<div class="detail-list-item last-item">是上和33含量为它的相应的结束</div>标签。有没有更好的方法来做到这一点,以防止这个文件的未来更新版本,以便我不必检查文件,以确保我没有删除错误的行?

最后一部分是我需要替换以前的html类以包含last-item作为第二类。所以最终的html会类似于:

<div class="dashlet"> 
    <div class="body"> 
    <div class="detail-list-item"> 
     <!-- some content here --> 
    </div> 
    <div class="detail-list-item"> 
     <!-- some more content here --> 
    </div> 
    <div class="detail-list-item"> 
     <!-- some more content here --> 
    </div> 
    <div class="detail-list-item last-item"> 
     <!-- some final content here --> 
     <!-- note how we are one div shorter and this div's class has a second class --> 
    </div> 
    </div> 
</div> 

什么sed命令可以完成此任务?

回答

2

由于sed逐行处理文件,因此它可能不是最好的解决方案。但是,由于您的文件是非常小的,你可以用这个这使整个文件到保持缓冲有点哈克的解决方案,并随后对整个文件替换一次:

sed -rni 'H;${x;s/\n(.*list-item)(".*)\n <div.* <\/div>/\1 last-item\2/p}' /path/to/file 

这里有一个解释:

# options: -r extended regex so parentheses don't need to be escaped 
#   -n don't automatically print pattern space 
#   -i edit file in place 
H;      # add the current line to the hold space 
$      # if we are at the last line 
    {     # commands until '}' are only run if at the last line 
    x;     # swap pattern space and hold space 
    s/     # search/replace 
     \n(.*list-item) # greedy match to the last 'list-item', put in group 1 
     (".*)   # double quote must follow 'list-item', match as many 
         # characters as possible and put in group 2 
     \n <div.* <\/div> # match all of the next (final) double-indented 
           # div, don't put it in a group 
    /
     \1 last-item\2 # insert ' last-item' before groups 1 and 2, final 
         # double-indented div will be deleted 
    /p    # print the result 
    } 

你可以做,你有更简单的命令来删除最后DIV部分:

sed -i '/<div.*last-item/,/<\/div>/d' /path/to/file 

不幸的是,我不知道一个简单的方法来添加last-item作为第二个类到最后的div。

相关问题