Reputation: 1556
Say i have a file structure like so:
stuff/
foo/
foo1.txt
foo2.txt
bar/
bar1.txt
other/
I'd like a bash command that finds all directories in the current directory in this case stuff/
and creates files with the names of these directories in another directory, in this case other/
with a desired extension eg. .csv
.
The result would look like this:
stuff/
foo/
foo1.txt
foo2.txt
bar/
bar1.txt
other/
foo.csv
bar.csv
Upvotes: 0
Views: 35
Reputation: 533
Try this:
#! /bin/bash
function read_and_cp() {
for file in `ls $1`
do
if [ -d $1/${file} ]; then
touch $2/${file}.csv
read_and_cp $1/${file} $2
fi
done
}
read_and_cp stuff other
Upvotes: 0
Reputation: 181745
The question is a bit light on the "what did you try" front, but I'll indulge you.
To list all directories, we can use find
:
$ cd stuff
$ find . -mindepth 1 -maxdepth 1 -type d
./bar
./foo
We can pipe this into a while
loop which uses read -r
to extract each successive directory name into a variable, here dirname
:
$ find . -mindepth 1 -maxdepth 1 -type d | while IFS="" read -r dirname; do echo $dirname; done
./bar
./foo
Finally, instead of echo
ing the directory name, we can run touch
to create the file with the desired name:
$ find . -mindepth 1 -maxdepth 1 -type d | while IFS="" read -r dirname; do touch ../other/$dirname.csv; done
$ ls ../other
bar.csv foo.csv
Alternative approach! Because there are many ways to skin a cat.
We can use ls -d */
to list all directories:
$ ls -d */
bar/ foo/
Then we use sed
to strip off the /
and add the path and file extension:
$ ls -d */ | sed 's#\(.*\)/#../other/\1.csv#'
../other/bar.csv
../other/foo.csv
Then we use xargs
to run a touch
for each of these filenames:
$ ls -d */ | sed 's#\(.*\)/#../other/\1.csv#' | xargs touch
$ ls ../other
bar.csv foo.csv
Upvotes: 1