Search code examples
bashshellscriptingbatch-rename

Batch editing files 'stuck at weird place'


I'm trying to learn how to batch edit files and extract information from them. I've begun with trying to create some trial files and editing their names. I tried to search but couldn't find the problem I'm in anywhere. If it's already answered, I'd be happy to be directed to that link.

So, I wrote the following code:

#!/bin/bash

mkdir -p ./trialscript
echo $1
i=1
while [ $i -le $1 ]  
do
    touch ./trialscript/testfile$i.dat
    i=$(($i+1))
done

for f in ./trialscript/*.dat 
do 
    echo $f
    mv "$f" "$fhello.dat"
done

This doesn't seem to work, and I think it's because the echo output is like:

4
./trialscript/testfile1.dat
./trialscript/testfile2.dat
./trialscript/testfile3.dat
./trialscript/testfile4.dat

I just need the filename in the 'f' and not the complete path and then just rename it. Can someone suggest what is wrong in my code, and what's correct way to do what I'm doing.


Solution

  • If you want to move the file, you have to use the path, too, otherwise mv wouldn't be able to find it.

    The target specification for the mv command is more problematic, though. You're using

    "$fhello.dat"
    

    which, in fact, means "content of the $fhello variable plus the string .dat". How should the poor shell know where the seam is? Use

    "${f}hello.dat"
    

    to disambiguate.

    Also, to extract parts of strings, see Parameter expansion in man bash. You can use ${f%/*} to only get the path, or ${f##*/} to only get the filename.