Cat命令结合重定向功能实现文本内容写入

本文介绍如何利用Cat命令结合重定向功能实现文本内容的写入、追加及格式保持等高级操作,并提供了脚本变量处理及特殊字符转义的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Cat命令结合重定向功能实现文本内容写入

  • 将stdin标准输入的内容重定向到test.txt文件(若此文件不存在,则创建),且当stdin中含有EOF时完成写入;
  • cat 追加内容用 >>,覆盖内容用 > ;
  • 其中EOF可以替换为任意字符串。

写入内容到文本,覆盖文本原有内容

cat > /root/test.txt << EOF
this is first line 
this is second line
this is thrid line
EOF

追加内容到文本,保留文本原有内容

cat >> /root/test.txt << EOF
this is fourth line
this is fifth line
EOF

脚本中的变量问题

文本中的$TAG变量会被直接赋值,对第一个EOF加引号即可避免

TAG=8.0
cat > /root/run_mysql.sh << "EOF"
#!/bin/bash
docker run -it -d \
    --name mysql \
    -e MYSQL_ROOT_PASSWORD=my-secret-pw \
    mysql:$TAG
EOF

文本内容中的缩进

如果文本存在缩进格式,使用tab制表符缩进无法保留其缩进格式,如果希望保留缩进格式,需要使用空格缩进

cat > /root/test.txt << EOF
linegroup1
	this is first line 
	this is second line
linegroup2
	this is thrid line
	this is fourth line
EOF

空格缩进执行结果

# cat test.txt 
linegroup1
    this is first line 
    this is second line
linegroup2
    this is thrid line
    this is fourth line

tab缩进执行结果

# cat test.txt 
linegroup1
this is first line 
this is second line
linegroup2
this is thrid line
this is fourth line

第二个EOF前含有制表符

如果在脚本中使用cat EOF并且存在如下缩进格式,可以看到第二个EOF前含有缩进:

cat test.sh 
#!/bin/bash
if true;
then
        cat > /root/test.txt <<- EOF
        this is first line
        this is second line
        this is thrid line
        EOF
fi

缩进存在两种情况:tab制表符缩进和空格缩进,这种缩进会导致制表符或空格被判定为结尾符,而非EOF,针对制表符缩进将第一个EOF改为<<- EOF格式即可解决。

man bash中的说明:

# man bash | grep "<<-"
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line  containing  delimiter.   This  allows

但是针对空格缩进该方法并不能解决问题,第二个EOF前如果为空格缩进必须修改为制表符缩进。

查看文本缩进格式,“^I”表示制表符,“$”表示换行符

:set list
:set list TAB 

直接将EOF输出传递给命令

# Create multiple YAML objects from stdin
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000000"
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep-less
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000"
EOF
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

willops

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值