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

时间:2013-10-14 08:52:15

标签: linux bash substring

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

This is the file.txt from my folder.

我试过了:

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

但我希望使用exprsedawk命令以更干净的方式制作它。

由于

编辑:

我找到了另一种方式(尽管如此,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

3 个答案:

答案 0 :(得分:14)

以下解决方案使用seds/(替换)来删除前导和尾随部分:

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

输出:

file.txt

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

^$符号可确保匹配完整的字符串。仅在文件名包含"from my folder.""This is the"

的特殊情况下才需要这样做

答案 1 :(得分:1)

如果'file.txt'是一个固定的字符串,并且不会改变,那么你可以这样做:

var="This is the file.txt from my folder"

请注意,您不需要将字符串回显到变量,只需在二进制“=”运算符的右侧键入它。

echo $var |sed -e 's/^.*\(file\.txt\).*$/\1/'

根据您的sed(1)版本,如果在sed(1)中有-r(扩展正则表达式)选项,则可以松开括号的转义。

如果'file.txt'发生了变化,那么您可以尽力创建模式,例如:

echo $var |sed -e 's/^.* \([^ ]\+\.[^ ]\+\) .*$/\1/'

答案 2 :(得分:0)

你可以尝试grep:

var=$(egrep -o file.txt)
相关问题