bash中的子字符串

时间:2014-06-18 17:49:53

标签: bash

我的字符串是长文件名,例如a.b.c.d.e.output。我想提取字段b,它可以是可变长度。

我怎么能这样做?我考虑过按.分割字符串并从中b,但我不确定如何在bash中执行此操作。

3 个答案:

答案 0 :(得分:2)

使用cut command

$ echo "a.b.c.d.e" | cut -d. -f2
b

答案 1 :(得分:2)

使用read,使用here字符串传递文件名:

IFS=. read a b rest <<< "$fname"

答案 2 :(得分:1)

对于这种特殊情况,你可以通过两个步骤在纯粹的bash中完成它:

# This removes from $fn the shortest prefix matching the glob *.
dropfirst=${fn#*.}
# This removes the longest suffix matching the glob .*
component2=${dropfirst%%.*}

这可以通过改变dropfirst来概括:

droptwo=${fn#*.*.}
dropthree=${fn#*.*.*.}

但请注意,如果没有足够的组件,$fn将会不加改变地传递。

总结:

#   drop shortest prefix matching pattern
##  drop longest prefix matching pattern
%   drop shortest suffix matching pattern
%%  drop longest suffix matching pattern.

模式可以使用任何标准的glob选项(*?[...]),如果你有shopt -s extglob,也可以使用扩展模式。