8

I'm a newbie to shell programming and have no idea how to solve this problem.

I just downloaded a file from the Internet to the default directory ~/Downloads. I want to move that file to another directory, ~/Documents.

Since I don't know the exact name of the downloaded file, I think I can use the following command to achieve my goal:

ls -t ~/Downloads | head -1 | mv [source] [destination]

How can I specify which formal parameter to replace. In my case, I want to omit [source] and fill in the [destination] parameter as ~/Documents myself.

3 Answers 3

5

You want xargs.

echo "foo" | xargs touch
ls -l foo
3
  • 1
    this is a really good hint (which is what the OP asked for) but you may want to note that this isn't actually a solution to the specific question
    – DQdlM
    Sep 25, 2011 at 12:37
  • +1. Enough for me to solve the problem. But @eldering gives a more elegant solution. :-) Sep 25, 2011 at 13:26
  • 2
    Only until you hit a file with a space. Sep 25, 2011 at 16:17
17
ls -t ~/Downloads | head -1 | xargs -I  {} mv ~/Downloads/{} ~/Documents

This will work with files that have spaces in their names.

14

You can also use bash' command substitution operator (backticks) as

mv `ls -t ~/Downloads | head -1` ~/Documents

as a one-shot solution if you do not want to move multiple files in one go. See the bash man-page:

Command Substitution
   Command  substitution  allows  the output of a command to replace the command name.  There
   are two forms:

          $(command)
   or
          `command`

   Bash performs the expansion by executing command and replacing  the  command  substitution
   with  the  standard  output  of the command, with any trailing newlines deleted.  Embedded
   newlines are not deleted, but they may be removed during word splitting.  The command sub‐
   stitution $(cat file) can be replaced by the equivalent but faster $(< file).

   When  the  old-style backquote form of substitution is used, backslash retains its literal
   meaning except when followed by $, `, or \.  The first backquote not preceded by  a  back‐
   slash terminates the command substitution.  When using the $(command) form, all characters
   between the parentheses make up the command; none are treated specially.

   Command substitutions may be nested.  To nest when using the backquoted form,  escape  the
   inner backquotes with backslashes.

   If  the  substitution  appears within double quotes, word splitting and pathname expansion
   are not performed on the results.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .