- Suppose we have a file
directories.txtwhere each line contains the name of a directory that we want to create. Our friend proposes that we run
cat directories.txt | mkdirinto order to do this? Will this command work? If not, how can we change this command to get it to work/could we improve it in any way?
One correct way to solve this is the command:
xargs mkdir < dir.txt
Many people might write this as the following. It’s fine, but it is a bit unnecessary to invoke the
cat command and using a
| when we already have input redirection (
cat dir.txt | xargs mkdir
- Come up with a general statement about when we need to use the
xargs whenever we want to take something that would be coming as input to use them as command-line arguments. So for the last problem, the list of files is coming from a file that we can only redirect as input, but
mkdir doesn’t read from
stdin, it only takes command-line arguments.
On top of this, people often think of using
xargs when you want to run one command over many possible input values.
- Suppose we want to run
Mystery.javaand save standard output to a file named
out1.txtand have it print standard output to the console. How would we achieve this?
java Mystery.java | tee out1.txt
- Again, suppose we are running
Mystery.java. This time, however, we want standard output and standard error to print to the console, in addition to having all output printed to
out1.txt. How would we achieve this?
java Mystery.java 2>&1 | tee out1.txt
- Suppose we have the
intro_survey.csvfrom the previous homework assignment. Using
cut, how many unique answers were there to the question “what is your favorite candy”?
tail -n+2 intro_survey.csv | cut-d, -f1 | sort -f | uniq -i | wc -l
- Write a command that would delete all directories, recursively, starting from the current directory. Be careful about where you run this command!! Don’t run it from your home directory!
find -type d | xargs rm