天天看点

Linux 文件追加内容

一、把内容写入到文件

1、echo命令

echo把指定内容写入文件并覆盖原有内容

[root@node-01 ~]# echo "hello,world" > readme.txt
[root@node-01 ~]# cat readme.txt
hello,world
      

echo把指定内容追加到文件末尾

[root@node-01 ~]# echo "world" >> readme.txt
[root@node-01 ~]# cat readme.txt 
hello
world
      

2、cat命令

创建新的文件readme.txt,并开始写入内容,直到输入EOF结束

[root@node-01 ~]# cat > readme.txt  <<EOF
> A
> B
> C
> EOF      

cat命令把内容追加到文件末尾

[root@node-01 ~]# cat >> readme.txt  <<EOF
> e
> f
> g
> EOF
[root@node-01 ~]# cat readme.txt 
hello
world
e
f
g
[root@node-01 ~]#       

二、从标准输入流读取数据写入文件

1、tee命令

tee命令从标准输入读取数据写入文件

[root@node-01 ~]# ping baidu.com | tee  readme.txt
PING baidu.com (220.181.38.251) 56(84) bytes of data.
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=1 ttl=128 time=29.4 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=2 ttl=128 time=29.7 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=4 ttl=128 time=31.9 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=5 ttl=128 time=45.4 ms
      

tee命令从标准输入读取数据追加到文件

[root@node-01 ~]# ping baidu.com | tee -a readme.txt
PING baidu.com (220.181.38.251) 56(84) bytes of data.
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=1 ttl=128 time=29.4 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=2 ttl=128 time=29.7 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=4 ttl=128 time=31.9 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=5 ttl=128 time=45.4 ms      

tee命令从把输入写入到多个文件

[root@node-01 ~]# ping baidu.com | tee -a readme.txt readme2.txt
PING baidu.com (220.181.38.251) 56(84) bytes of data.
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=1 ttl=128 time=29.4 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=2 ttl=128 time=29.7 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=4 ttl=128 time=31.9 ms
64 bytes from 220.181.38.251 (220.181.38.251): icmp_seq=5 ttl=128 time=45.4 ms      

继续阅读