For the input section of a script, I wrote a snippet using a while
loop and an if
statement to check whether there are matches for the $search
. Only if there are matches does it move on to the input of $replace
; if there are no matches it asks for $search
again.
while true; do
echo "Please enter token to be replaced: "
read -e -r search
match="$(find . -maxdepth 1 -path "*${search}*" -printf "." | wc -c)"
if [ "${match}" -gt 0 ]; then
echo "${match} file(s) found"
break
else
echo "no matches found!"
echo
fi
done
echo "Please enter replacement: "
read -e -r replace
# I used the following command to check if the output was right
# echo "rename 's/$search/$replace/g' ./*"
In this snippet I used advice I got from a question I asked on Stack Overflow.
This code is going to be used as the input section of a rename script. In the last line I added an echo "rename...
command to check if the output works as expected.
The script is meant to process all files matching the $search
criteria in the current directory. Therefore I used find . -maxdepth 1...
.
The script of which this snippet is part of got reviewed here earlier.
Does this code match general standards?
1 Answer 1
If you want to match by the same pattern as rename
,
then it's probably best to use perl
.
To be really pedantic and support filenames with embedded newlines,
you could use -print0
of find
,
and then in perl
split the output by 0円
characters and filter with the grep
function:
find . -maxdepth 1 -print0 | perl -ne "print scalar grep /$search/, split /0円/"
Putting in your script:
while true; do
echo "Please enter token to be replaced: "
read -e -r search
match=$(find . -maxdepth 1 -print0 | perl -ne "print scalar grep /$search/, split /0円/")
if [ "${match}" -gt 0 ]; then
echo "${match} file(s) found"
break
else
echo "no matches found!"
echo
fi
done
-
\$\begingroup\$ Thank you janos, this works perfect! Looks like after all I kind of have to (at least a little) get into perl :-) AWESOME! \$\endgroup\$nath– nath2017年08月03日 22:00:53 +00:00Commented Aug 3, 2017 at 22:00
-path
uses a shell pattern, whiles///
uses a regular expression. Therefore, if you search fora.c
, fileabc
won't be found byfind
, even thoughrename
would match and rename it. Similarly,a?c
would findabc
, but replace won't match it. \$\endgroup\$find . -maxdepth 1 -regextype sed -regex "*${search}*" -printf "." | wc -c
but I did not get it to work. Also I wasn't sure witchregextype
to choose, I thoughtsed
was the closest torename
, but please correct me... \$\endgroup\$rename
uses perl regexes which might be unsupported byfind
. \$\endgroup\$