如何仅从文件名中提取一个下划线分隔的字段? [英] How can I just extract one underbar-separated field from a filename?

查看:58
本文介绍了如何仅从文件名中提取一个下划线分隔的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的文件名列表:

I have a list of file names like this:

REG_2016120200hourly_d01_20161202_00_00_00.nc

我要提取这个名字并放入一个变量:

Of this name I would like to extract and put in a variable:

1)日期20161202

1)date 20161202

    for file in /path/*;
    do
     filename=$(basename -- "$file")
     date=${filename:4:8}
     echo $date
    done

这有效,脚本给了我 20161202 ,我不知道为什么

and this is working, the script give me 20161202 and I don't know why

2)时间步00

我需要先取两个零0,然后尝试使用

I need to take the firsts two zero 00 and I'm trying with

timestep = $ {filename:34:36} ,但这不起作用.

我有点惊讶,因为我在其他脚本中使用了相同的方法,但是我从未遇到过问题.

I'm a little bit surprised because I used the same method in other scripts and I have never had problems.

谢谢

推荐答案

timestep="${filename:34:2}"

2 是长度.

来自 man bash :

$ {parameter:offset:length} :子字符串扩展.从offset指定的字符开始,扩展到参数值的最大长度字符.[...]

${parameter:offset:length}: Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by offset. [...]

这篇关于如何仅从文件名中提取一个下划线分隔的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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