I have a list that looks like this in a file called names.txt:
JOHN DOE
JANE DOE
ADAM SMITH
SARAH BROWN
SUSIE JOHNSON
Is there a script that I can run in the Terminal that will create folders from each line in this list?
Answer
There's an easy way to run a command for each line of a text file, and it doesn't require a script which would be overkill for a single command like mkdir. Use the xargs command like this:
xargs -tI % mkdir % < names.txt
The -I option tells xargs to run a command for each line from STDIN. In this case, STDIN comes from reading the names.txt file with < names.txt. The % character is a replacement string that xargs uses to as a placeholder for a line from the file. This means that everywhere xargs sees % in the command, % is replaced by a line from the file.
The -t option causes xargs to print each command before it's executed. It's not necessary, but it can be helpful for more complicated problems.
When xargs runs with the sample file, the output looks like this:
mkdir JOHN DOE
mkdir JANE DOE
mkdir ADAM SMITH
mkdir SARAH BROWN
mkdir SUSIE JOHNSON
and the mkdir commands make a new folder with the names from the names.txt file.
No comments:
Post a Comment