Bash script to extract keywords from current directory Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Bash script to extract keywords from current directory without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.]

We are here to answer your question about Bash script to extract keywords from current directory - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji