我想使用sed从servername
filenames_for_severname_all
echo "filenames_for_servername_all" | sed -n 's|filenames_for_\(*\)_all|\1|p'
以上都没有回报。谁能解释一下?
答案 0 :(得分:3)
您的正则表达式无效,在*
修饰符之前缺少一个标记(例如.
将匹配任何字符):
echo "filenames_for_servername_all" | sed -n 's|filenames_for_\(.*\)_all|\1|p'
您也可以尝试grep
:
echo "filenames_for_servername_all" | grep -o 'filenames_for_\(.*\)_all'
答案 1 :(得分:3)
Pure BASH方式:
s="filenames_for_servername_all"
[[ "$s" =~ _for_([^_]+) ]] && echo "${BASH_REMATCH[1]}"
servername
或者awk:
awk -F_ '{print $3}' <<< "$s"
servername
OR cut:
cut -d_ -f3 <<< "$s"
servername