sed第一次出现文本替换

时间:2012-04-25 13:31:12

标签: sed

我想删除每个.x文件中两个单词之间的文字,我尝试过:

find temp -type d | while read DIRNAME
do
    sed -i '/abcd1/,/abcd2/d' ~/Desktop/$DIRNAME/.x
done

问题是我想删除第一次出现的这个,但是

sed -i '0,/abcd1/,/abcd2/d' ~/Desktop/$DIRNAME/.x

不起作用。

3 个答案:

答案 0 :(得分:1)

sed -ie 'bb; :a q; :b s/from/into/; ta' test.txt
  • bb; - 转移到b标记(跳过q uit命令);
  • :a q; - a标记q uit命令;
  • :b s/from/into - b标记替换;
  • ta - 如果替换成功,请跳至a标记;
  • ; - sed。中的命令分隔符。

希望它有所帮助。

答案 1 :(得分:1)

一种方式:

sed -e '/3/,/6/ { /6/ ba ; d }; b ; :a ; $! { N ; ba }; s/[^\n]*\n//'

编辑解释一下:

/3/,/6/         # Range between line that matches '3' and other line that matches '6'.
{
  /6/ ba        # When matches last line of the range, goto label 'a'.
  d             # Delete each line in the range.
}
b               # This command will be executed in lines until first match in the 
                # range. It prints the line and begin loop reading next one.
:a              # Label 'a'.
$!              # While not found last line ...
{ 
  N             # Append next line to current pattern space.
  ba            # Go to label 'a'. Enter a loop reading each line until last one.
}
s/[^\n]*\n//    # Remove until first '\n' (content of last line of the range) and print 
                # the rest.

测试

infile的内容:

1
2
3
4
5
6
7
1
2
3
4
5
6
7

像以下一样运行:

sed -e '/3/,/6/ { /6/ ba ; d }; b ; :a ; $! { N ; ba }; s/[^\n]*\n//' infile

输出(仅删除'3'和'6'之间的行):

1
2
7
1
2
3
4
5
6
7

答案 2 :(得分:0)

这可能对您有用:

sed '/word1/!b;:a;/word1.*word2/{s///;tb};$!{N;ba};:b;$!{n;bb}' file

以上是单词的用途,对于使用的行块:

sed '/block1/,$!b;x;/./{x;b};x;/block1/,/block2/{/block2/h;d}' file

编辑:

删除first occurence, only if there are more than one occurrences

 sed '/word1/!b;:a;/\(word1\).*\(word2\)\(.*\1.*\2\)/{s//\3/;tb};$!{N;ba};:b;$!{n;bb}' file