0

I have a directory hierarchy named, for example, abc and a text file names.txt. I need to choose several lines from the text file and then create new files with sample text, say "Hello world", in every sub-directory of the abc, where every chosen line from the names.txt is the name for one of the new files. I have to do it in one line using xargs or -exec. I've tried something like this but it doesn't seem to work:

find abc -type d -exec sh -c 'grep ^'A' names.txt | xargs -I% sh -c 'echo 'Hello world' | tee {}/%'' \;

How to do this the right way?

1
  • What "doesn't work" about it, exactly? – Jeff Schaller Dec 12 '18 at 12:06
2

Let's start with what you need to for one directory:

awk '/^A/ { print "Hello world" >$0 }' names.txt

This would read the file called names.txt and write the string Hello world to each filename given by a complete line of input from that file, if the input line starts with a capital A.

With a small modification, we can get it to output to a file under a specific directory, $dirname:

awk -v dir="$dirname" '/^A/ { print "Hello world" >(dir "/" $0) }' names.txt

We may then use find to call this for each subdirectory (including the start directory):

find abc -type d -exec awk -v dir={} '/^A/ { print "Hello world" >(dir "/" $0) }' names.txt \;
5
  • @StéphaneChazelas Yes, print >(expression) appears to work. – Kusalananda Dec 12 '18 at 13:30
  • @StéphaneChazelas The issue with using -execdir here is that the names.txt file has to be given with an absolute pathname. That's not difficult to organize though... – Kusalananda Dec 12 '18 at 13:32
  • Ah OK, sorry, I thought the names.txt was to be found in each directory. Then that won't work. With -execdir, the command runs in the parent of the file being found (hence the -name names.txt -execdir...). – Stéphane Chazelas Dec 12 '18 at 13:36
  • @StéphaneChazelas In, the parent, of course. Doh. – Kusalananda Dec 12 '18 at 13:38
  • Note that the dir={} assumes a version of find that expands {} when found as part of arguments, and that directory names don't contain backslash characters. – Stéphane Chazelas Dec 12 '18 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.