代码之家  ›  专栏  ›  技术社区  ›  Makstvell

linux bash->sed(正则表达式)。如何用“source_dir”和“target_dir”替换所有出现的已定义节,以替换source_dir节中的内容

  •  0
  • Makstvell  · 技术社区  · 1 年前

    例如,我有这样的文本:

    <<<<<<<<< <<source_dir>>
    tesst
    <<<<<<<<< <<target_dir>>
    tes23442141
    <<<<<<<<<
    good
    safasf
    
    <<<<<<<<< <<source_dir>>
    tesst241241
    <<<<<<<<< <<target_dir>>
    tes23442141
    <<<<<<<<<
    
    safasfas
    

    部分是

    <<<<<<<<< <<source_dir>>
    [any text -> first text]
    <<<<<<<<< <<target_dir>>
    [any text -> second text]
    <<<<<<<<<
    

    我想将所有这部分替换为仅第一个文本

    例如,输出必须为:

    tesst
    good
    safasf
    
    tesst241241
    
    safasfas
    

    我有这样的sed:

    sed -e ':a;N;$!ba;s#<<<<<<<<< <<source_dir>>\n\(.*\)\n<<<<<<<<< <<target_dir>>.*<<<<<<<<<#\1#g' "$target_file"   
    

    但作为输出,我有:

    tesst
    <<<<<<<<< <<target_dir>>
    tes23442141
    <<<<<<<<<
    good
    safasf
    
    <<<<<<<<< <<source_dir>>
    tesst241241
    
    safasfas
    

    还有问题我该怎么解决?) 我理解这个问题,但我不明白该怎么做> 请帮帮我!

    1 回复  |  直到 1 年前
        1
  •  0
  •   Karapys_Mor    1 年前

    最简单的解决方案是排除字符 < 从regex:

    sed -e ':a;N;$!ba;s#<<<<<<<<< <<source_dir>>\n\([^<]*\)\n<<<<<<<<< <<target_dir>>[^<]*<<<<<<<<<#\1#g' "$target_file"
    

    输出

    tesst
    good
    safasf
    
    tesst241241
    
    safasfas
    

    请注意,如果文本包含字符 < ,这行不通。