I hope this is not a duplicate, because it may be very basic in bash, but I always find similar questions, but with different outcomes. I have many subdirectories, each of it containing a "aaa.txt" file, which is the only txt file in the subdirectory. The txt filename is always the same (so in the example above, is always "aaa", in each subdirectory). I need to add the subdirectory name to the txt files. So assuming I have ./AAA/aaa.txt and ./BBB/aaa.txt, the results of the script should be: ./AAA/AAA_aaa.txt and ./BBB/BBB_aaa.txt

1 Answer 1


You can use dirname command to get the directory name and the basename command to get the file name, then construct your desired destination name. Assuming you are using only one directory level, you can set, for example


and do the rename with

mv "$FILEPATH" "$(dirname "$FILEPATH")/$(dirname "$FILEPATH")_$(basename "$FILEPATH")"
  • thank you for your reply. Maybe I am missing something, but your solution didn't work for me. I had this error: mv: target 'AAA_aaa.txt' is not a directory Do you know why this is happening?
    – ginopino
    Jun 4, 2020 at 23:48
  • Not sure. Could you put an echo in front of the command to see what bash thinks you are trying to do... echo mv $FILEPATH $(dirname $FILEPATH)/$(dirname $FILEPATH)_$(basename $FILEPATH)
    – orylis
    Jun 5, 2020 at 0:07
  • Sure, this is what I get: mv AAA/aaa.txt BBB/aaa.txt AAA BBB/AAA BBB_aaa.txt. By the way, I find a solution for my problem here: stackoverflow.com/questions/14306117/…
    – ginopino
    Jun 5, 2020 at 0:16
  • Good to hear you found a solution.
    – orylis
    Jun 5, 2020 at 0:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .