【问题标题】:sed first occurrence text replacementsed 首次出现的文本替换
【发布时间】:2019-01-30 11:39:12
【问题描述】:

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

没用。

【问题讨论】:

  • 能否给出一个示例文件,预期结果和实际结果?

标签: sed


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

希望对你有帮助。

【讨论】:

    【解决方案2】:

    一种方式:

    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
    

    【讨论】:

    • 我意识到,只有当有两个或多个出现时,我才需要删除第一个出现。我尝试使用变量和 if 条件,但没有成功。
    【解决方案3】:

    这可能对你有用:

    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
    

    【讨论】:

    • 谢谢你的回复,这行得通,但如果我只有一次出现它被删除并且我不想要这个,我需要删除第一个出现,只有当有超过一次。
    • 好的,请参阅编辑以获取新解决方案。
    • 感谢您的宝贵时间,但这对文件没有任何影响,我使用了 "sed -i '/x/!b;:a;/(abcd1).*(abcd2)(. *\1.*\2)/{s//\3/;tb};$!{N;ba};:b;$!{n;bb}' test.x" 我有一个文件有两个abcd1 abcd2的出现
    • 对不起,我的错误,第一次搜索应该是/word1/,我会修改解决方案。
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2011-08-10
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多