How to create a file in Linux from terminal window

2019-01-15 23:59发布

What's the easiest way to create a file in Linux terminal?

15条回答
倾城 Initia
2楼-- · 2019-01-16 00:04

This will create an empty file with the current timestamp

touch filename
查看更多
欢心
3楼-- · 2019-01-16 00:08

Also, create an empty file:

touch myfile.txt
查看更多
We Are One
4楼-- · 2019-01-16 00:09

There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

查看更多
Ridiculous、
5楼-- · 2019-01-16 00:11

Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit

查看更多
干净又极端
6楼-- · 2019-01-16 00:13

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist

查看更多
对你真心纯属浪费
7楼-- · 2019-01-16 00:14

Simple as that :

> filename

查看更多
登录 后发表回答