0

I have tried searching for similar questions but can't find anything so apologies if this or similar has been asked before.

I am writing a script to read a textfile list of file names with a reference number then looking through subfolders for those files, then amending the name to include the ref num.

The text file will look like this (tab delimited and with header) :

"File Name (without Extension)"  "Media Number"
"AK7A7964"  "01017134"
"IMG_0026"  "01017192"
"106491 Anenome"  "01017206"
"CW1_9449"  "01017243"

I am using this to clean the file of \t and ":

 cat $file | sed "1 d" | tr "\\t" "," | sed 's/\"//g' > $cleanfile

Then reading the cleanfile into a while loop:

INPUT=$cleanfile
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read fname media; do

And constructing the new name to be amended to the start of the filename

newFileName="MA_${media}_"

I'm then doing a find for each file with that name using:

for found in $(find . -type f  -name "$fname.*" ); do

but when I try to amend the name, it only alters the last result if there are multiple files with the same name found.

I'm probably missing a trick in doing this using sed but I can't find a guide that doesn't go off in the deep end quite quickly!

[edit to add]

What I was doing after the last do was this: Getting the path and basename, creating the new file name, then using mv to replace it. I was actually just doing an echo so it was non-destructive

foundPath="${found%/*}"
foundFile="${found##*/}"

newFile=$newFileName$foundFile
newFilePath="${foundPath}/${newFile}"
mv $found $newFilePath

If there was more than one occurrence of any filename (as there will be), it was only mv'ing the last one.

6
  • it would be helpful if you included what you're doing after do in your loops.
    – I0_ol
    Commented Oct 7, 2016 at 15:34
  • The loop won't work if the name has a space in it, like 106491 Anenome.
    – Barmar
    Commented Oct 7, 2016 at 15:36
  • How is your while read loop using , as the delimiter between fname and media?
    – Barmar
    Commented Oct 7, 2016 at 15:37
  • Also you don't need cat. sed "1 d" "$file" | tr "\\t" "," | sed 's/\"//g' > "$cleanfile"
    – I0_ol
    Commented Oct 7, 2016 at 15:39
  • @user556068 Ive updated the details of whats happening after in the for found in $(find . -type f -name "$fname.*" ); do section
    – chriszanf
    Commented Oct 10, 2016 at 11:07

1 Answer 1

0

The solution I found was this:

find . -type f -name "${fname}.*" -exec sh -c 'for i; do name=${i##*/} path=${i%/*}; mv "$i" "$path/MA_${media}_$name"; done' _ {} +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.