linux极简小知识:31、在linux中创建文件并写入内容【最简单操作】

9,351 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

有两种方式,可以非常简单的在Linux的shell命令行中,创建一个文件并写入内容。一个是使用echo命令输出,另一个是使用vi/vim创建编辑文件。

echo输出内容到文件

echo最常见的用法是在终端打印(或输出)字符串。通过重定向符号>>>,可以实现将文本内容,输出到文件中(覆盖或追加)。

'echo xx >`输出内容到文件

echo "string" > test.txt 用于将字符串写入test.txt文件,文件不存在将会创建,存在则覆盖。

如下,测试echo写入文件:

[root@VM_0_15_centos ~]# mkdir test
[root@VM_0_15_centos ~]# cd test/
[root@VM_0_15_centos test]# ls -al
total 8
drwxr-xr-x   2 root root 4096 Sep 21 14:02 .
dr-xr-x---. 22 root root 4096 Sep 21 14:02 ..
[root@VM_0_15_centos test]# echo "this is my write file test\n测试写入" > test.txt
[root@VM_0_15_centos test]# cat test.txt
this is my write file test\n测试写入

'echo xx >>`追加内容到文件

echo "string" >> test.txt 用于将字符串追加写入test.txt文件。

[root@VM_0_15_centos test]# echo "append to file test">>test.txt
[root@VM_0_15_centos test]# cat test.txt
this is my write file test\n测试写入
append to file test
[root@VM_0_15_centos test]#

echo -e输出文内容换行

echo -e参数用于处理特殊字符。

比如上面输出内容中\n作为换行符处理,如下覆盖输出到文件:

# echo -e "this is my write file test\n测试写入" > test.txt
# cat test.txt
this is my write file test
测试写入

echo中的多行内容(输出多行内容到文件中)

echo后用引号包含的内容,可以直接使用回车换行,即引号中可以为多行内容。

这样,可以实现输出多行到文件中:

# echo "hello
> world
> I am a multiple lines content">>mulline.txt
# cat mulline.txt
hello
world
I am a multiple lines content

vi/vim创建编辑文件【极简】

使用vi/vim也可以很方便的创建编辑文件。如下,很简单的三步实现编辑文件。

  1. vi file打开或创建并打开文件
# vi test1.txt
  1. vi/vim编辑器中,输入i进入insert模式,可编辑文字

  1. 写完文字后,Esc退出insert模式,输入:进入命令行模式,输入wq!,按回车保存并退出vi/vim。

这样就完成了一个文件的创建编辑。

查看编辑的文件:

# cat test1.txt
我是使用vi创建的新文件
回车换行