Search code examples
shellfor-loopprepend

Prepend text to beginning of file names


I would like to prepend a string of text to the beginning of each file in a directory. The string is uniwisc.

When I run the script:

#!/bin/sh

url="ftp://rammftp.cira.colostate.edu/Lindsey/spc/ir/"

wget -r -nd --no-parent -nc -P /awips2/edex/data/goes14/ $url

find /awips2/edex/data/goes14/ -type f -exec cp {} /awips2/edex/data/uniwisc/ \;

for f in /awips2/edex/data/uniwisc/*; 
    do
    f="$(basename $f)"
    mv "$f" "uniwisc.$f"
    done;

find /awips2/edex/data/uniwisc/ -type f -mmin -6 -exec mv {} /awips2/edex/data/manual/ \;
exit 0

I get the error mv: cannot stat '<filenames>' "No such file or directory.


Solution

  • There are a number of different ways that you can do that.

    Using paramater expansion, which is built into the bash shell:

    for f in <dir path>/*; do
        mv "$f" "${f%/*}/uniwisc.${f##*/}"
    done
    

    Using the rename command:

    rename 's!^!uniwisc.!' *
    

    Using the basename, as CodeGnome suggested:

    for f in <dir path>/*; do
        mv "$f" "$(dirname "$f")/uniwisc.$(basename "$f")"
    done
    

    I was going to write more methods, but there are a lot of them and they don't change significantly. Personally, I'd use the rename command in that situation.