0

我想删除每个 .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

不起作用。

4

3 回答 3

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

希望能帮助到你。

于 2012-04-25T13:43:53.117 回答
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
于 2012-04-25T13:47:57.317 回答
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
于 2012-04-26T06:45:41.150 回答