如何在bash中获取两个特定字符之间的字符串(不使用grep或sed)?
例如:
input=hostname~web:sit
我希望从上述输入中提取 web
${hostname#*~}
的输出结果是 web:sit
,但我只需要输出结果中的 web
从其他帖子中可以看到
% 从 $var 的结尾开始删除到指定模式的字符。
但不确定如何应用它。
请帮忙解决,谢谢!
使用 extglob
在 bash
中,你可以用一步完成以下操作:
shopt -s extglob
input='hostname~web:sit'
echo "${input//@(*~|:*)/}"
web
这里的@(*~|:*)
匹配从开头到~
字符或从:
到结尾的子字符串。使用//
,我们将所有这样的实例替换为空字符串。
还有一个sed
解决方案:
sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"
web
web
。 - undefinedshopt
行的部分。请尝试现在更新的答案。 - undefined请分两步进行:
input=hostname~web:sit
rightpart=${input#*~} # remove prefix up to "~" (included)
output=${rightpart%:*} # remove suffix from ":" (included)
echo $output
另一个选项是使用cut
,它可从GNU Core Utilities获得:
~
后面的所有内容:
前面的所有内容input='hostname~web:sit'
echo "$input" | cut -d '~' -f2 | cut -d ':' -f1
# web
sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"
- undefinedawk -F '[~:]' '{print $2}' <<< "$input"
- undefinedsed/grep
中实现。请理解bash
是一种不同的语言,而grep/sed/awk
则是另一种。 - undefined