Home > Net >  Append file name with source folder using the FIND command
Append file name with source folder using the FIND command

Time:01-27

I need to strip files out of a number of directories that all have the same file name a.txt. The difference comes from the parent folder so

example1\a.txt example2\a.txt ...

so I am hoping to run a FIND command that will capture a.txt but not overwrite the file as it moves from folder to folder. so the output would be

example1_a.txt example2_a.txt

So from another post the FIND command I want is the following

find . -name "a.txt" -execdir echo cp -v {} /path/to/dest/ \;

So I want to modify in some way to append the source folder to the file. so my guess is to manipulate {} somehow to do it.

Thanks in advance

CodePudding user response:

A one liner might be possible, but you could use this:

#!/bin/bash

targetprefix="targetdir"
find . -name "a.txt" -print0 | while read -r -d '' line
do
    path=$(dirname "$line")
    newpath=$(echo "${path#./}" | tr '/' '_')
    target="$targetprefix/$newpath"
    
    filename=$(basename "$line")
    
    cp -v $line $target/$filename
done
  • change variable "targetprefix" to be the destination directory you desire.
  • this find with -print0 and while comes from https://mywiki.wooledge.org/BashFAQ/001
  • since results from find all start with "./", I use "${path#./}" to remove that prefix.
  • the tr replaces all subsequent "/" with an underscore. This will take care of sub directories
  • WARNING: I did not test all "weird" directory and filename formats for proper execution (like carriage returns in filenames!).
  • Related