linux - 带有正则表达式的 Bash 子字符串

标签 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

最佳答案

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

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/

相关文章:

XML XSLT 转换。三种环境,三种不同的行计数,使用 Oracle 的 xml util

c - 为什么我的变量值被删除了?

java - 将两个字符串分成子字符串并将它们配对

c - 指针值在函数调用过程中发生变化

python - Windows 到 Linux 脚本问题 : "IndexError: list index out of range"

python - 如何使用 ctypes 加载链接到非默认 libc 的库?

java - 从 ANT 任务执行 Bower 更新

bash - 将 xargs Bash 命令转换为 PowerShell?

regex - 两个看似相同的 sed 命令,一个有效,另一个无效。你能告诉我为什么吗?

mysql - 搜索子字符串并返回 'true' 或 'false' 的 SQL 条件