bash 在bash中提取两个引号之间的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35636323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:19:14  来源:igfitidea点击:

extracting a string between two quotes in bash

bash

提问by Vik

I have example string like Test "checkin_resumestorevisit - Online_V2.mt" Run

我有像这样的示例字符串 Test "checkin_resumestorevisit - Online_V2.mt" Run

and i want to extract the text between the two quotes in bash. I tried using command like

我想在 bash 中提取两个引号之间的文本。我尝试使用类似的命令

SUBSTRING=${echo $SUBSTRING| cut -d'"' -f 1 }

but it fails with error: bad substitution.

但它失败了error: bad substitution

回答by Arton Dorneles

In order to extract the substring between quotes you can use one of these alternatives:

为了提取引号之间的子字符串,您可以使用以下替代方法之一:

Alternative 1:

备选方案 1:

SUBSTRING=`echo "$SUBSTRING" | cut -d'"' -f 2`

Alternative 2:

备选方案 2:

SUBSTRING=`echo "$SUBSTRING" | awk -F'"' '{print }'`

Alternative 3:

备选方案 3:

set -f;IFS='"'; SUBSTRING=($SUBSTRING); SUBSTRING=${SUBSTRING[1]};set +f

回答by Charles Duffy

If you want to extract content between the first "and the last ":

如果要提取第一个"和最后一个之间的内容"

s='Test "checkin_resumestorevisit - Online_V2.mt" Run'
s=${s#*'"'}; s=${s%'"'*}
echo "$s"

回答by bufh

Other weird ideas to not let @arton-dornelesalone :^)

其他不让@arton-dorneles一个人呆着的奇怪想法:^)

But my favourite is @charles-duffyanswer.

但我最喜欢的是@charles-duffy 的回答。

[[ "$SUBSTRING" =~ \"(.*)\" ]] && SUBSTRING="${BASH_REMATCH[1]}"

IFS=\" read -r _ SUBSTRING _ <<<"$SUBSTRING"

# bonus, match either ' or " by pair
SUBSTRING=$(echo "$SUBSTRING" | sed -r "s/.*?([\"'])(.*).*//")

Note that bash create a temporary file for "here string" (<<<) as it does for here documents.

请注意,bash 为“here string” ( <<<)创建一个临时文件,就像它为 here 文档所做的那样。

Edit

编辑

It took me way too long to fully understand Charles Duffy critics; for readers, this could be when:

我花了很长时间才完全理解查尔斯·达菲 (Charles Duffy) 的批评者;对于读者来说,这可能是:

SUBSTRING='*"inside text" outside text'

In this scenario, the following would be unsafe because the star would be expanded, listing files and moving the desired result index:

在这种情况下,以下内容将是不安全的,因为星号将被扩展,列出文件并移动所需的结果索引:

IFS=\" eval '_=($SUBSTRING);SUBSTRING="${_[1]}"'

IFS=\" read -ra _ <<<"$SUBSTRING";SUBSTRING=${_[1]}