在 Bash 中提取子字符串 [英] Extract substring in Bash

查看:24
本文介绍了在 Bash 中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 someletters_12345_moreleters.ext 形式的文件名,我想提取 5 位数字并将它们放入一个变量中.

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

所以为了强调这一点,我有一个包含 x 个字符的文件名,然后是一个五位数字序列,两边各有一个下划线,然后是另一组 x 个字符.我想取 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. I want to take the 5 digit number and put that into a variable.

我对实现这一目标的不同方式非常感兴趣.

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

推荐答案

使用 cut:

echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2

更通用:

INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING

这篇关于在 Bash 中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆