如何使用bash为另一个文件夹中的每个目录创建新文件?

如何使用bash为另一个文件夹中的每个目录创建新文件?,bash,filesystems,command-line-interface,Bash,Filesystems,Command Line Interface,假设我有这样一个文件结构: stuff/ foo/ foo1.txt foo2.txt bar/ bar1.txt other/ 我想要一个bash命令,它在本例中查找当前目录中的所有目录stuff/,并在另一个目录中使用这些目录的名称创建文件,本例中为other/,具有所需的扩展名,例如.csv 结果如下所示: stuff/ foo/ foo1.txt foo2.txt bar/ bar1.txt other/ foo.csv ba

假设我有这样一个文件结构:

stuff/
  foo/
   foo1.txt
   foo2.txt
  bar/
   bar1.txt
other/
我想要一个bash命令,它在本例中查找当前目录中的所有目录
stuff/
,并在另一个目录中使用这些目录的名称创建文件,本例中为
other/
,具有所需的扩展名,例如
.csv

结果如下所示:

stuff/
  foo/
   foo1.txt
   foo2.txt
  bar/
   bar1.txt
other/
  foo.csv
  bar.csv

这个问题在“你尝试了什么”方面有点浅显,但我会放纵你的

要列出所有目录,我们可以使用
find

$ cd stuff
$ find . -mindepth 1 -maxdepth 1 -type d
./bar
./foo
我们可以将其导入
while
循环,该循环使用
read-r
将每个连续的目录名提取到一个变量中,这里是
dirname

$ find . -mindepth 1 -maxdepth 1 -type d | while IFS="" read -r dirname; do echo $dirname; done
./bar
./foo
最后,我们可以运行
touch
以创建具有所需名称的文件,而不是
echo
ing目录名:

$ find . -mindepth 1 -maxdepth 1 -type d | while IFS="" read -r dirname; do touch ../other/$dirname.csv; done
$ ls ../other
bar.csv  foo.csv

另一种方法!因为给猫剥皮的方法很多

我们可以使用
ls-d*/
列出所有目录:

$ ls -d */
bar/  foo/
然后我们使用
sed
去除
/
并添加路径和文件扩展名:

$ ls -d */ | sed 's#\(.*\)/#../other/\1.csv#'
../other/bar.csv
../other/foo.csv
然后我们使用
xargs
为每个文件名运行
touch

$ ls -d */ | sed 's#\(.*\)/#../other/\1.csv#' | xargs touch
$ ls ../other
bar.csv  foo.csv
试试这个:

#/bin/bash
函数read_和_cp(){
对于'ls$1'中的文件`
做
如果[-d$1/${file}];则
触摸$2/${file}.csv
读取\u和\u cp$1/${file}$2
fi
完成
}
阅读和其他内容

感谢您的帮助,我尝试了类似于“查找”命令的方法,但使用了cut<代码>查找-键入d-exec'cut-d”/“-f2我认为
-exec
只是直接运行命令,而不经过shell,所以