I am trying to write a one line command to create 20 empty files with names extracted from a .txt file in another folder directory with the same txt extension.

I tried

for i in $(cat test.txt); do grep -w $i | touch $i.txt ; done


cat test.txt| while read line ; do grep $line ; touch $line.txt ; done

as well as

for filename in $(cat testfile.txt) ;  do touch head -20 $filename.txt; done

It does not work. I do not know how to specify the 10 first words of the test.txt file.

  • How about for i in $(head test.txt); do touch $i.txt ; done? – mikewhatever Oct 21 at 13:50
  • 2
    Please edit your question to include a minimal example of your test.txt file - the format matters e.g. whether there is one word per line, multiple words per line etc. – steeldriver Oct 21 at 13:55
  • ...or rather for i in $(head -n 20 test.txt); do touch $i.txt ; done, since you want 20 entries. – mikewhatever Oct 21 at 15:01
  • 1
    @Fred007... you mean 20 first words? – bac0n Oct 21 at 15:58

Does this work for you?

while IFS= read -r i; do
  touch "$i".txt
done < <(head -20 filename.txt)
  • 1
    Not sure why this was downvoted - although I'd suggest replacing the command substitution + here string with a process substitution + redirection i.e. done < <(head -20 filename.txt) and adding a -r to the read in case any of the filenames contain escapes. Arguably it should be while IFS= read -r i; do if we assume that any leading whitespace is intentional. I guess we should wait for clarification from the OP. – steeldriver Oct 21 at 15:03
  • 1
    I would use while IFS= read -r i – pa4080 Oct 21 at 17:39

Get first 20 words.

Using cut:

$ for i in $(cut -d ' ' -f1-20 a.txt); do touch $i.txt; done

(with mapfile):

$ mapfile -d ' ' -n 20 -t < a.txt; touch ${MAPFILE[@]/%/.txt}

(with awk):

$ awk '{for (i=1; i<=20; i++) {system("touch "$i".txt")}}' a.txt

(with shell parameter expansion):

$ a=($(<a.txt)); a=(${a[@]/%/.txt}); touch ${a[@]:0:19}
  • it worked thanks bac0n – Fred007 Oct 21 at 18:48

xargs command has --arg-file flag, which allows using arguments for a command you intend to run from file. Thus, you can do

xargs --arg-file=filenames.txt touch

If you want first 20 lines

head -n20 filenames.txt | xargs  touch

Substitute tail instead of head for last 20 lines from file

  • he wants 20 words. – bac0n Oct 22 at 6:16
  • 1
    @bac0n That's not been confirmed yet, but I'll edit my answer if that is in fact so – Sergiy Kolodyazhnyy Oct 22 at 6:40

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.