I wrote a bash shell script for Linux to move files in a static folder according to parameters specified in a data file.
I've reduced that script to a minimal reproducible example to demonstrate an issue I'm having with it:
#!/bin/bash
while IFS=" " read -r fldr matchStr
do
perlExp=\'s/^/\\/home\\/test\\/alpha\\/"$fldr"\\//\'
fullmatchStr=testfile\ -\ "$matchStr"\ -\ *.txt
rename --verbose "$perlExp" ${fullmatchStr}
done < test.dat
(Please note that I originally started out using mv
instead of rename
, and I'm fine with using either command.)
This script reads test.dat
, which is a text file of the syntax:
folderName matchStr
...
A simple example of this test.dat
file:
test001 *.foo.bar
test002 *.foo.baz
test003 bar.*.baz
It is essential that wildcards are allowed in this data file and are supported by the script. Also, support for spaces within filenames is required.
Examples of filenames of files to be moved:
testfile - linux.foo.bar - 10101010 10101010.txt
testfile - unix.foo.bar - 01010101 10101010.txt
testfile - ubuntu.foo.baz - 10101010 01010101.txt
testfile - debian.foo.baz - 10101010 00000000.txt
testfile - bar.linus.baz - 11111111 01010101.txt
Given the above test.dat
file, those files need to be moved, respectively, to these folders:
/home/test/alpha/test001
/home/test/alpha/test001
/home/test/alpha/test002
/home/test/alpha/test002
/home/test/alpha/test003
I read several relevant QAs, including:
- mv: cannot stat No such file or directory in shell script
- https://stackoverflow.com/questions/8748831/when-do-we-need-curly-braces-around-shell-variables
- Why does my shell script choke on whitespace or other special characters?
but I'm still not getting the results I desire. No errors are presented, but no files are moved.
How can this piece of code be improved to make it work as desired?
fullmatchStr="testfile - $matchStr - *.txt"
would be a much easier-to-read way to write the exact assignment your code already contains. Mind. if you want to actually replace that glob with a set of matching names, you should probably just store the names directly:names=( "testfile - $matchStr - "*.txt )
, which will give you an array which can be expanded with"${names[@]}"
.