如何在创建时写入文本文件?

How to write to a text file upon creation?

我正在自学命令行代码,似乎找不到答案。

我正在使用标准的 MacOS 终端应用程序来创建 directories/files 以供练习。

我的问题是,我可以使用代码来包含在创建文件时写入文件的内容吗?

我试过:

touch one/texttest.txt echo "Hello"

但这只会在 "one" 文件夹

中创建 3 个文件,一个名为 hello,一个名为 echo,第三个名为 texttest.txt

我也试过这些并得到了相同的结果:

touch echo "Hello" ~/one/texttest.txt

echo Hello ~/one/texttest.txt

touch one/texttest.txt Hello

我似乎无法为带有 0 个插件的标准终端应用程序找到任何解决方案,这可能吗?

这应该有效:

echo "Hello" > one/texttest.txt
touch one/texttest.txt echo "Hello"

这是带有三个参数的 touch 命令:one/texttest.txtechoHello(shell 删除了引号)。

touch echo "Hello" ~/one/texttest.txt
touch one/texttest.txt Hello

这些与第一个相同(不同的论点但相同的概念)。

echo Hello ~/one/texttest.txt

这是带有两个参数的 echo 命令:Hello~/one/texttest.txt(只有 ~ 会在 echo看到了)。

touch 只创建文件(并更新时间戳)它不写入内容。

您可以有一个 touch 命令也可以获取内容,但我不知道有一个。

幸运的是你不需要一个,因为 shell 可以为你做这件事。

你使用 echo Hello 到 运行 echo 并让它吐出 Hello 然后你告诉 shell 到 "redirect" 文本到文件而不是屏幕。

echo Hello > texttest.txt

值得指出的是,无论您是否写入任何内容,重定向都会创建文件(事实上,无论命令是否有效,甚至是否存在,或者即使给出了命令)。

$ ls /tmp/texttest.txt
ls: /tmp/texttest.txt: No such file or directory
$ flekjfe Hello > /tmp/texttest.txt
$ ls /tmp/texttest.txt
/tmp/texttest.txt

因此您可以单独使用 > file 创建一个新的空文件。

您可以使用输出重定向 command_output > 文件

更多详情:http://tldp.org/LDP/abs/html/io-redirection.html