linux bash -> sed(正则表达式)。如何将所有出现的定义部分替换为“source_dir”和“target_dir”到source_dir部分中的内容

问题描述 投票:0回答: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

并询问我该如何解决它?) 我明白这个问题,但我不明白该怎么做> 请帮助我!

linux bash sed replace posix
1个回答
0
投票

最简单的解决方案是从正则表达式中排除字符

<

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

输出:

tesst
good
safasf

tesst241241

safasfas

请注意,如果文本包含字符

<
,则此操作无效。

© www.soinside.com 2019 - 2024. All rights reserved.