How to Read Lines from a Text File and Create a Text File for Each Name

bashcommand line

Let's say I have a text file like:

john
george
james
stewert

with every name on a separate line.

I want to read the lines of this text file and create a text file for each name, like: john.txt, george.txt etc.

How can I do this in Bash?

Best Answer

#1 Using Bash + touch:

while read line; do touch "$line.txt"; done <in
  • while read line; [...]; done <in: This runs read until read itself returns 1, which happens when when the end of the file is reached; the input for read is read from a file named in in the current working directory instead of from the terminal due to the <in redirection;
  • touch "$line.txt": This runs touch on the expanded value of $line.txt, which is the content of line followed by .txt; touch will create the file if not existing and update its access time if existing;

#2 Using xargs + touch:

xargs -a in -I name touch name.txt
  • -a in: makes xargs read its input from a file named in in the current working directory;
  • -I name: makes xargs replace every occurence of name with the current line of input in the following command;
  • touch name: Runs touch on the replaced value of name; it will create the file if not existing and update its access time if existing;
% ls
in
% cat in
john
george
james
stewert
% while read line; do touch "$line.txt"; done <in
% ls
george.txt  in  james.txt  john.txt  stewert.txt
% rm *.txt
% xargs -a in -I name touch name.txt
% ls
george.txt  in  james.txt  john.txt  stewert.txt
Related Question