Search code examples
bashfilenamesparameter-expansion

How can I just extract one underbar-separated field from a filename?


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)date 20161202

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

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

2)timestep 00

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

timestep=${filename:34:36} but this doesn't work.

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

Thank you


Solution

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

    2 is length.


    From man bash:

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