I have 4 directories: dir1 dir2 dir3 dir4. I want to create a file in each directory. I know I can do this: touch file1.txt and then move it to dir1, then touch file2.txt then move it to dir2 but it takes ages. How can I create a function that creates a text file in each of the directories? Thanks
2 Answers
You don't need to create and then move files - you can touch
them in place ex.
touch dir1/file1.txt dir2/file2.txt dir3/file3.txt
It won't really save you any time (or typing) but you can of course create a shell function for this - a minimal implementation would be
mkfile() { touch "$1"/"$2"; }
which you can invoke as
mkfile dir1 file1.txt
although of course it should really include some checking / error handling (such as what to do if $1
is not a directory, or doesn't exist).
If your file and directory structure is always of the form dirN/fileN.txt
then there are some better ways to automate the creation such as
seq 1 3 | xargs -I{} touch dir{}/file{}.txt
or even (using GNU parallel
and brace expansion)
parallel touch dir{}/file{}.txt ::: {1..3}
Not sure what you regard as 'ages'. There's no function that would create 4 files in parallel for you. Assuming you're using bash or similar the 'easiest' way is probably a loop. e.g.:
DIR=dir
for i in 1 2 3 4
do
touch "${DIR}i"
done
That's pretty quick on any machine I use. If you want an atomic 4 file create, I'm afraid there's no real way to do this.
Note that if there's content in the 4 files, the 'quickest' way in terms of lag between the first file appearing and the last one would be create the files elsewhere and then mv
them.
-
what does ${DIR}i do? Does it take input from user? I can't take input from user in my code unfortunately. Is there a way to put this loop in a function?– Jim6834Oct 20, 2019 at 12:23
-
In bash ${DIR} expands the value of the variable DIR (Which was previously set to the text 'dir' on the line above the for statement) The loop therefore runs 4 times. Performing touch dir1 touch dir2 touch dir3 touch dir4 What (scripting?) language are you writing in?– HamishOct 20, 2019 at 13:37
dir
andfile
prefixes? BTW you don't need to move files after, you can create them in place ex.touch dir1/file1.txt
touch dir1/file1.txt
and so on