简体   繁体   English

从方括号中提取字符串

[英]Extract string from square brackets

I need to get the value myfile.ext from this example string: 'My message [file:myfile.ext]' 我需要从以下示例字符串中获取值myfile.ext'My message [file:myfile.ext]'

I saw a similar question , but couldn't manage to make the string returns empty string if the brackets are not in the string. 我看到了类似的问题 ,但是如果方括号不在字符串中,则无法使字符串返回空字符串。

I need to check if the string contains [file:***] and return to the variable the *** otherwise must be empty value. 我需要检查字符串是否包含[file:***]并返回变量***否则必须为空值。

You can use grep for this: 您可以为此使用grep

$ grep -Po '(?<=\[file:)[^]]*(?=])' file
myfile.ext

Which is the same as (depending if you are reading from a file or piping): 这与(取决于您是从文件还是管道读取)相同:

$ echo "'My message [file:myfile.ext]'" | grep -Po '(?<=\[file:)[^]]*(?=])'
myfile.ext

Explanation 说明

It looks for the string coming after [file: and up to next ] . 它查找[file: and up to next ]之后的字符串。 To store it into a variable, use the var=$(command) expression: 要将其存储到变量中,请使用var=$(command)表达式:

result=$(grep -Po '(?<=\[file:)[^]]*(?=])' file)

it will be empty as default, and myfile.ext otherwise. 默认情况下为空,否则为myfile.ext

Sample 样品

$ cat a
My message [file:myfile.ext
My message [file:myfile.ext]]a]

$ grep -Po '(?<=\[file:)[^]]*(?=])' a
myfile.ext

您可以使用sed的-n标志来禁止打印所有行,然后在正则表达式中专门使用p标志来打印匹配项:

sed -n 's/\[file:\([^\]*\)]/\1/p' file

You can use this BASH regex: 您可以使用以下BASH正则表达式:

[[ "$s" == *[* ]] && [[ "$s" =~ \[[^:]*:([^\]]+)\] ]] && echo "${BASH_REMATCH[1]}"
myfile.ext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM