Adding directory name to filename

Nils Kassube kassube at gmx.net
Fri Mar 5 07:57:58 UTC 2010


Sam Albers wrote:
> I'm looking for a way to rename a bunch of files. I've searched but I
> haven't found any references on what I would like to be doing. Maybe
>  there isn't a way to do what I am thinking.
> 
> I would like to rename files by adding the directory name where a
>  particular file is located to the filename. So in a situation like
>  this, where I have:
> 
> /A/B/1.txt
> /A/B/2.txt
> /A/C/1.txt
> /A/C/2.txt
> 
> 
> I would like to have all the *.txt files renamed to reflect which
>  directory they are in like so
> 
> /A/B/B1.txt
> /A/B/B2.txt
> /A/C/B1.txt
> /A/C/B2.txt

I suppose the last two should rather be this:

/A/C/C1.txt
/A/C/C2.txt

Anyway, I would do it with a few lines of bash code, something like 
this:

for f in A/*/*.txt;do
  fn=$(basename "$f")
  d=$(dirname "$f")
  dn=$(basename "$d")
  mv "$f" "$d/$dn$fn"
done


Nils




More information about the ubuntu-users mailing list