如何从命令行创建空文件
如何从命令行创建空文件?
使用touch
命令:
The touch utility sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.
例:
touch newfile
> newfile
还会创建一个空文件。 如果该文件已存在,则将被截断 (清空)。 要保留文件内容,请使用>>
进行追加,如下所示:
>> file
即使文件存在,内容也不会受到影响。
编辑 :如果您没有要输入的内容,这个内容会更快:
user@host$ :> newfile user@host$ :>> new_or_existing_file
注意。 :
是命令。 它不是提示的一部分。
cat /dev/null > file1.ext
确切的方式还有另一种方式
echo "" > file2.ext
不同之处在于file1.ext将为零字节,file2.ext将为一个字节。 你可以检查一下
ls -l file*.*
使用vim
编辑器,您还可以创建一个空文件。
vim filename
然后保存
:wq
命令
echo -n > file
如果您的echo
版本支持-n开关,则创建一个空文件。
或者你可以使用printf
printf '' > file
Python单线程:
$ python -c 'import sys,os;f=sys.argv[1];os.utime(f,None) if os.path.exists(f) else open(f,"a").close' myfile.txt
基本上,python实现了touch
。
我们可以缩短它:
$ python -c 'import sys,os;f=sys.argv[1];'$'\n''with open(f,"a"): os.utime(f,None)' mysecondfile.txt