使用正则表达式的Bash子字符串

Lui*_*cía 6 linux bash substring

在bash脚本中,我想从给定的字符串中提取变量字符串.我的意思是,我想file.txt从字符串中提取字符串:

This is the file.txt from my folder.
Run Code Online (Sandbox Code Playgroud)

我试过了:

var=$(echo "This is the file.txt from my folder.")
var=echo ${var##'This'}
...
Run Code Online (Sandbox Code Playgroud)

但我倒是喜欢,使其在一个更清洁的方式使用expr,sedawk命令.

谢谢

编辑:

我发现了另一种方式(尽管如此,sed命令的答案对我来说是最好的):

var=$(echo 'This is the file.txt from my folder.')
front=$(echo 'This is the ')
back=$(echo ' from my folder.')
var=${var##$front}
var=${var%$back} 
echo $var
Run Code Online (Sandbox Code Playgroud)

Dan*_* S. 15

以下解决方案使用seds/(取代)以除去前缘和后部分组成:

echo "This is the file.txt from my folder." | sed "s/^This is the \(.*\) from my folder.$/\1/"
Run Code Online (Sandbox Code Playgroud)

输出:

file.txt
Run Code Online (Sandbox Code Playgroud)

\(\)包围,我们要保留的部分.这被称为一个组.因为它是我们在此表达式中使用的第一个(也是唯一的)组,所以它是组1.我们稍后在替换字符串中引用该组\1.

^$体征确保整个字符串匹配.这仅适用于文件名包含"from my folder."或的特殊情况"This is the".