简体   繁体   中英

Passing shell script variables to find

I'm working on recursively renaming directories and files in a directory.

alan/
    alan_0001.txt
    alan_0002.txt
andy/
    andy_0001.txt
    andy_0002.txt
andytwo/
    andytwo_0001.txt
    andytwo_0002.txt

I have a tab delimited file (hopefully reproduced here) that supplies new information for file names; eg

alan     123_123     Alan's Place
andy     124_010     Andy's Place
andytwo     125_001     Andy's Second Place

I've worked out the following shell script, but I'm not sure how to pass values from early in the script to find at the end.

#!/bin/sh

FILE="sample-list.txt"

exec 3<&0
exec 0<$FILE

while read line
do
    echo $line
    oldName=`echo "$line" | cut -f1`
    adminDB=`echo "$line" | cut -f2`
    title=`echo "$line" | cut -f3`
    echo "$oldName is old, his number is $adminDB, and the title is $title"
    echo "renaming files"
#    echo find -name '{$oldName}*' 
    echo "`find ./ -name '${oldName}*'`"
done
exec 0<&3

I'd like to throw the wildcard on $oldName to catch the andy_0001, _0002 files and rename them with find ./ -name ${oldName}* -exec rename $oldName $adminDB {} \\;

Thanks in advance!

I think you just need to use double quotes:

find ./ -name "${oldName}*" -exec rename $oldName $adminDB {} \;

You can also save some code by letting the shell split the input line into fields:

while read oldName adminDB title; do
    ...
done

You would lose the original whitespace from the full line, so if that is important, ignore this unsolicited advice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM