Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

string - 在Bash中提取子字符串(Extract substring in Bash)

Given a filename in the form someletters_12345_moreleters.ext , I want to extract the 5 digits and put them into a variable.

(给定文件名格式someletters_12345_moreleters.ext ,我想提取5位数字并将其放入变量中。)

So to emphasize the point, I have a filename with x number of characters then a five digit sequence surrounded by a single underscore on either side then another set of x number of characters.

(因此,为了强调这一点,我有一个文件名,其中包含x个字符,然后是一个五位数的序列,在两侧用单个下划线包围,然后是另一组x个字符。)

I want to take the 5 digit number and put that into a variable.

(我想使用5位数字并将其放入变量中。)

I am very interested in the number of different ways that this can be accomplished.

(我对实现此目标的许多不同方式非常感兴趣。)

  ask by Berek Bryan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If x is constant, the following parameter expansion performs substring extraction:

(如果x为常数,则以下参数扩展将执行子字符串提取:)

b=${a:12:5}

where 12 is the offset (zero-based) and 5 is the length

(其中12是偏移量(从零开始),而5是长度)

If the underscores around the digits are the only ones in the input, you can strip off the prefix and suffix (respectively) in two steps:

(如果数字中的下划线是输入中唯一的数字,则可以分两步(分别)去除前缀和后缀:)

tmp=${a#*_}   # remove prefix ending in "_"
b=${tmp%_*}   # remove suffix starting with "_"

If there are other underscores, it's probably feasible anyway, albeit more tricky.

(如果还有其他下划线,尽管比较棘手,但这仍然是可行的。)

If anyone knows how to perform both expansions in a single expression, I'd like to know too.

(如果有人知道如何在一个表达式中执行两个扩展,我也想知道。)

Both solutions presented are pure bash, with no process spawning involved, hence very fast.

(提出的两种解决方案都是纯bash,不涉及任何流程生成,因此非常快。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...