我是 shell 编程的新手,不知道如何解决这个问题。
我刚刚从互联网上下载了一个文件到默认目录~/Downloads
。我想将该文件移动到另一个目录~/Documents
。
由于我不知道下载的文件的确切名称,所以我认为我可以使用以下命令来实现我的目标:
ls -t ~/Downloads | head -1 | mv [source] [destination]
我如何指定要替换哪个形式参数。就我而言,我想省略[source]
并填写我自己的[destination]
参数~/Documents
。
答案1
你要xargs
。
echo "foo" | xargs touch
ls -l foo
答案2
ls -t ~/Downloads | head -1 | xargs -I {} mv ~/Downloads/{} ~/Documents
这将适用于名称中带有空格的文件。
答案3
您还可以使用 bash 的命令替换运算符(反引号)作为
mv `ls -t ~/Downloads | head -1` ~/Documents
如果您不想一次移动多个文件,可以将其作为一次性解决方案。请参阅 bash 手册页:
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.