Sed:从字符串中提取servername

时间:2014-01-16 07:32:22

标签: linux sed

我想使用sed从servername

中提取filenames_for_severname_all
echo "filenames_for_servername_all" | sed -n 's|filenames_for_\(*\)_all|\1|p'

以上都没有回报。谁能解释一下?

2 个答案:

答案 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