简体   繁体   中英

How to create files with folder names recursively using script?

I have a folder structure that can have x subfolders, like so:

  • Folder 1
    • Sub-folder 1
    • Sub-folder 2
      • Sub-sub-folder 3
  • Folder 2

I want to create an empty file that has the name of the sub-folders (with.file appended) in their parent folders, as presented here:

  • Folder 1
    • Sub-folder 1.file (newly created file that has the same name as the sister folder)
    • Sub-folder 1
    • Sub-folder 2.file (newly created file that has the same name as the sister folder)
    • Sub-folder 2
      • Sub-sub-folder 3.file (newly created file that has the same name as the sister folder)
      • Sub-sub-folder 3
  • Folder 2

Some folders might have spaces in their names, so I've tried the following but it's not working even though echoing $(dirname $dir)/$dir seems to yield the expected result:

#!/bin/bash

find . -mindepth 1 -type d | while read dir
do
    touch $(dirname $dir)/$dir.file
done

What would be the best way to achieve this? Thank you so much in advance!

post updated to try to be clearer

perhaps you could try:

find . -type d | while IFS= read -r d
do 
    ( cd "$d" && cd .. && touch "$(basename "$d").file" ) 
done

I have tried with awk, check this if its useful for you. I am giving.file for file name

 realpath Fol*/* | awk '{print "touch "$1".file"}' | sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM