linux用cat命令创建一个文件,用cat在命令行创建文件

我们常常使用cat命令来将某个文件的内容一口气打印出来查看,其实,cat命令还可以用来在命令行创建文件。

cat在命令行创建文件与vi不同,只能单行编辑,换行之后就不能再编辑前面的行;与echo编辑多行文件有点相似。

创建 test1.info 文件,按Ctrl+d退出:

[xinlin@localhost ~]$ cat > test1.info

this is test1.info

hello...

[xinlin@localhost ~]$ cat test1.info

this is test1.info

hello...

cat > file,将标准输入的内容写入file,所见即所得,Ctrl+d结束,适合交互式的创建文件。

可以使用另外一种很cool的方式来结束某个文件的编辑,即在cat命令中设置一个结束符,一般我们使用EOF。这就是我们常常见到的cat << EOF。

创建 test2.info 文件,使用EOF结束符:

[xinlin@localhost ~]$ cat > test2.info << EOF

> this is test2.info

> hello again...

> EOF

[xinlin@localhost ~]$ cat test2.info

this is test2.info

hello again...

用这种方式比Ctrl+d方式要清晰一点。每次换行之后,能看到一个换行提示符(>)。

把<< EOF放在前面也可以:

[xinlin@localhost ~]$ cat << EOF > test3.info

> this is test3.info

> hello anyway...

> EOF

[xinlin@localhost ~]$ cat test3.info

this is test3.info

hello anyway...

在EOF前后加引号也可以:

[xinlin@localhost ~]$cat > test4.info << 'EOF'

> this is test4.info

> no more hello

> EOF

[xinlin@localhost ~]$cat > test5.info << "EOF"

> this is test5.info

> HELLO in uppercase.

> EOF

[xinlin@localhost ~]$ cat test4.info test5.info

this is test4.info

no more hello

this is test5.info

HELLO in uppercase.

cat命令行里的引号,跟shell脚本中的引号不一样,只是引号而已,加不加都没关系,双引号也不能解析shell变量。

[xinlin@localhost ~]$cat > test6.info << "EOF${key}"

> this is test6.info

> hi..

> EOF9

> EOF${key}

[xinlin@localhost ~]$ cat test6.info

this is test6.info

hi..

EOF9

可见,输入EOF9并不能结束输入。

同时,我们发现,EOF这三个字母其实并不是必须的,EOF只是一个习惯用法,End Of File,Linux系统内一切都是文件。其实,我们可以使用任意自己喜欢的结束符字符串。

[xinlin@localhost ~]$ cat > test7.info << abcde

> this is test7.info

> hi again

> abc

> abcd

> abcde

[xinlin@localhost ~]$ cat > test8.info << k

> this is test8.info

> hi all

> a

> b

> k

[xinlin@localhost ~]$ cat test7.info test8.info

this is test7.info

hi again

abc

abcd

this is test8.info

hi all

a

b

一个字母也可以作为结束符。

除了新建文件,还可以是对某个文件的追加写入:

[xinlin@localhost ~]$cat >> test8.info << EOF  # 使用>>,追加写入

> C

> D

> E

> EOF

[xinlin@localhost ~]$ cat test8.info

this is test8.info

hi all

a

b

C

D

E

注意:使用Ctrl+d的方式退出和使用<< eof的方式退出,编写的文件不太一样:

[xinlin@ifos ~]$ cat > t.sh

echo '$-'

echo '$$'

echo "$-"

echo "$$"

[xinlin@ifos ~]$ cat t.sh

echo '$-'

echo '$$'

echo "$-"

echo "$$"

[xinlin@ifos ~]$ cat > t.sh << eof

> echo '$-'

> echo '$$'

> echo "$-"

> echo "$$"

> eof

[xinlin@ifos ~]$ cat t.sh

echo 'himBH'

echo '1638'

echo "himBH"

echo "1638"

使用<< eof的方式退出,无论如何都会做变量替换,要注意这个细节;

使用Ctrl+d的方式退出,所见即所得!

以上就是使用cat命令创建文件的总结。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值