0

I have example sub-directory names such as:

  • Test_ABCDEF_406_1
  • Test_ABCDEF_AOH_1
  • Test_ABCDEF_AUQ_1

within a larger directory called Test.

How can I efficiently pull out "ABCDEF_**_" or everything after Test_ to get the following:

  • ABCDEF_406_1
  • ABCDEF_AOH_1
  • ABCDEF_AUQ_1

Note that the above are folders and not files if that makes a difference.

1 Answers1

1

You iterate over the pathnames of the subdirectories and use a parameter substitution to delete the initial part of them:

#!/bin/sh

for dirpath in Test/Test_*/; do # Because of the pattern used above, we know that # "$dirpath" starts with the string "Test/Test_", # and this means we know we can delete that:

# But first delete that trailing /
dirpath=${dirpath%/}

shortname=${dirpath#Test/Test_}

printf 'The shortened name for "%s" is "%s"\n' "$dirpath" "$shortname"

done

The substitution ${variable#pattern} is a standard substitution that will delete the (shortest) match of pattern from the start of the value $variable.

Likewise, ${variable%pattern}, used to delete the trailing / in the code, deletes the shortest match of pattern from the end of the value $variable.

Testing on the following directory tree:

.
`-- Test/
    |-- Test_ABCDEF_406_1/
    |-- Test_ABCDEF_AOH_1/
    `-- Test_ABCDEF_AUQ_1/

the code would produce

The shortened name for "Test/Test_ABCDEF_406_1" is "ABCDEF_406_1"
The shortened name for "Test/Test_ABCDEF_AOH_1" is "ABCDEF_AOH_1"
The shortened name for "Test/Test_ABCDEF_AUQ_1" is "ABCDEF_AUQ_1"
Kusalananda
  • 333,661
  • Isn't that syntax specific to bash? – Alexis Wilke Mar 18 '21 at 19:32
  • @AlexisWilke None of this is bash-specific. This would work on any shell that is aiming to be POSIX-compliant. sh, bash, zsh, yash, ksh, ... – Kusalananda Mar 18 '21 at 19:34
  • @Kusalananda So if I just wanted the output ABCDEF_406_1, ABCDEF_AOH_1, etc., do I just need to do: print $shortname ? – MAtennis9 Mar 18 '21 at 19:37
  • @ASinha You have the short name in $shortname, so you would output only that or do whatever it is that you actually want it for. I outputted a bit more to illustrate how to do it, but you could use printf '%s\n' "$shortname", or just echo "$shortname" if you were sure that it would be safe (see https://unix.stackexchange.com/questions/65803). – Kusalananda Mar 18 '21 at 19:39
  • @Kusalananda great, that worked perfectly. Thank you! – MAtennis9 Mar 18 '21 at 19:42