To get the K
from LposK.dat
, if that string is in $name
, we may do
k=${name%.dat} # remove ".dat" suffix
k=${k##*pos} # remove everything up to end of (the last) "pos"
This would work even if $name
was a pathname like some/path/LposK.dat
(and even if some/path
contained the string pos
), which is useful when we later plug it into find
.
To move one file:
k=${name%.dat}
k=${k##*pos}
dest="$HOME/destination/$k"
mkdir -p "$dest" && mv "$name" "$dest" # only move if mkdir did not fail
With find
:
find . -type f -name '*pos*.dat' -exec sh -c '
for name do
k=${name%.dat}
k=${k##*pos}
dest="$HOME/destination/$k"
mkdir -p "$dest" && mv "$name" "$dest"
done' sh {} +
This would give the internal sh -c
script a number of pathnames as arguments, and the script would iterate over these, moving each one into the correct subdirectory of $HOME/destination
.
Related:
If your files are in a single subdirectory (the current directory), then you can do this even easier without find
:
for name in ./*pos*.dat; do
[ ! -f "$name" ] && continue # skip non-regular files
k=${name%.dat}
k=${k##*pos}
dest="$HOME/destination/$k"
mkdir -p "$dest" && mv "$name" "$dest"
done