从给定子字符串前缀和后缀的变量中删除所有出现的子字符串

问题描述 投票:0回答:1

举个例子,我有一个变量包含:

sentence="\<Name\>Mary\</Name\> has a little lamb it's fleece as white as snow and everywhere that \<Name\>Sharon\</Name\> went the lamb was sure to go. \<Name\>Lucy\</Name\>, \<Name\>Mary\</Name\> quite contrary how does your garden grow?"

并且我需要删除(所有出现的)前缀

\<Name\>
和后缀
\</Name\>
之间的所有内容,包括前缀和后缀字符串本身以获得:

sentence=" has a little lamb it's fleece as white as snow and everywhere that  went the lamb was sure to go. ,  quite contrary how does your garden grow?"

我不知道如何实现这一目标。有人有 sed、awk 等解决方案吗?

bash awk sed substring
1个回答
0
投票

最好的方法是使用 sed,如下所示:

#!/bin/bash
sentence="<Name>Mary</Name> has a little lamb it's fleece as white as snow and everywhere that <Name>Sharon</Name> went the lamb was sure to go. <Name>Lucy</Name>, <Name>Mary</Name> quite contrary how does your garden grow?"

# Use sed to remove everything between <Name> and </Name>, including the tags
cleaned_sentence=$(echo "$sentence" | sed 's/<Name>[^<]*<\/Name>//g')

echo "$cleaned_sentence"
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.