You could do everything in Perl, or everything in a shell script. Mixing languages is usually a bit messy though.
The shell script version may look something like this (with bash
, for example):
#!/bin/bash
dirs=( *.frames )
for dir in "${dirs[@]}"; do
printf 'Working on "%s"\n' "$dir"
cd "$dir"
digitfiles=( RawImage_?.tif )
for file in "${digitfiles[@]}"; do
newfile="RawImage_0${file#RawImage_}"
mv "$file" "$newfile"
done
stackname="../$dir.mrc"
tif2mrc -s *.tif "$stackname"
cd ..
done
for f in *.mrc; do
mv -- "$f" "${f%%.*}".mrc
done
Or, slightly more idiomatic (now with plain sh
, but using a find
that understands -execdir
):
#!/bin/sh
echo 'Renaming TIFF files'
find *.frames -type f -name 'RawImage_?.tif' \
-execdir sh -c 'mv "$1" "RawImage_0${1#RawImage_}"' sh {} ';'
for d in *.frames; do
printf 'Processing "%s"...\n' "$d"
tif2mrc -s "$d"/*.tif "${d%%.*}.mrc"
done
(both examples are tested only with regards to filename generation)
Change sh -c
to sh -cx
to get a bit of output for each renamed file, or add -print
before -execdir
.
With -execdir
, the given shell command will be executed with the directory of the found file as its working directory. {}
(and $1
within the subshell) will be the basename of the found file.
If tif2mrc
needs to be run inside the directory of the TIFF files, then change the loop to
for d in *.frames; do
printf 'Processing "%s"...\n' "$d"
(cd "$d" && tif2mrc -s *.tif "../${d%%.*}.mrc" )
done
Note that in Perl, using backticks to execute a shell command will return the output of that command. You may instead use
system("tif2mrc -s *.tif $stackname");
if you're not interested in the output of tif2mrc
.
Also, it's confusing to read a script or program that changes directories back and forth. It can additionally lead to unwanted things if a directory does not exist (the chdir("..");
would then take you up one directory level too high).
To properly do this, either execute the command with a displaced working directory, as in my last shell example, or properly check the return code of the initial chdir()
in Perl (this would potentially still lead to code that may be hard to read and follow).
"${f%.*}"
instead of using%%
– glenn jackman Sep 18 '17 at 01:15f
isa.frames.mrc
, they may want to generatea.mrc
. With a single%
, they would just remove themrc
suffix and add it again. – Kusalananda Sep 18 '17 at 08:43