Bash script to extract keywords from current directory

I have a directory in the following format:


where X is a number, Y, Z, and A are 3 or 4 character long strings.

I want to write a shell script file that does the following:

  • extract X and Z from the folder name
  • create the string /folder1/folder2/name_(X-1)_Y_Z_A
  • copy the file string_Z.dat from that directory

I’m lost as to how to extract specific patterns from $PWD. The character positions of X and Z don’t have to be the same, as the number length and the length of name can vary.


You can first trim the leading path components using the shell’s parameter substitution syntax ${PWD##*/}, then read the basename into an array using underscores as a field separator:

IFS=_ read -a arr <<< "${PWD##*/}"

Since bash arrays are zero-indexed, the parts you want should be in ${arr[1]} and ${arr[3]} e.g.


[Note: I have assumed that you mean the arithmetic result of (X-1) rather than the literal string.]

Leave a Reply

Your email address will not be published. Required fields are marked *