在 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'}
...
但我想使用 expr
、sed
或 awk
命令以更简洁的方式实现它。
谢谢
已编辑:
我找到了另一种方法(尽管如此,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
最佳答案
以下解决方案使用 sed
和 s/
(替换)来删除前导和尾随部分:
echo "This is the file.txt from my folder." | sed "s/^This is the \(.*\) from my folder.$/\1/"
输出:
file.txt
\(
和\)
包含了我们想要保留的部分。这称为组。因为它是我们在此表达式中使用的第一个(也是唯一一个)组,所以它是第 1 组。我们稍后在替换字符串中用 \1
引用这个组。
^
和$
符号确保匹配完整的字符串。这仅在文件名包含 “来 self 的文件夹”
或 “This is the”
的特殊情况下才有必要。
关于linux - 带有正则表达式的 Bash 子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356593/