Adding directory name to filename

Nils Kassube kassube at gmx.net
Fri Mar 5 08:33:29 UTC 2010


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

That is a bit dangerous because it doesn't check if there is a file with 
the new name. This would be better:

for f in A/*/*.txt;do
  fn=$(basename "$f")
  d=$(dirname "$f")
  dn=$(basename "$d")
  n="$d/$dn$fn"
  test -e "$n" && echo "not renaming $f - $n exists" || mv "$f" "$n" 
done


Nils




More information about the ubuntu-users mailing list