shell 追加指定内容至某文件

本文详细介绍了sed命令在文本编辑中的应用,包括在文件首尾添加内容、查找并插入行、覆盖和追加操作,以及特殊字符转义。通过实例演示了如何在CSS代码中添加注释和修改指定行。

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

主要用的的脚本命令

sed -i '1i 添加的内容' file    #这是在第一行前  添加字符串

sed -i '$i 添加的内容' file    #这是在倒数第二行添加字符串

sed -i '$a 添加的内容' file    #这是在最后一行**添加一行**字符串

echo '内容' > file    #覆盖之前内容,文件只显示添加后的内容

echo '内容' >> file  #追加内容至最后一行**行后**

sed -i '/指定内容/a\要添加的内容' file   # 在包含指定内容的行后面增加一行

sed -i '/指定内容/i\要添加的内容' file    # 在包含指定内容的行前面增加一行

实践

文件内容

.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}

指定内容

this is sed test!!

测试脚本

sed -i '1i 添加的内容' file    #这是在第一行前  添加字符串

输出:
this is sed test!!
.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}
sed -i '$i 添加的内容' file    #这是在最后一行**行前**添加字符串

输出:
.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
this is sed test!!
}
sed -i '$a添加的内容' file    #这是在最后一行**行后**添加字符串

输出:
.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}
this is sed test!!
echo '内容' > file    #覆盖之前内容,文件只显示添加后的内容

输出:
this is sed test!!
echo '内容' >> file  #追加内容至最后一行**行后**

输出:
.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}this is sed test!!
sed '/^.page/a\#!/bin/bash' file

输出:
.page {
#!/bin/bash
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}
sed '/^.page/i\#!/bin/bash' file

输出:
#!/bin/bash
.page {
  padding: 0;
}
.text-demo-title {
  margin-left: 30rpx;
  margin-top: 30rpx;
}
.text-demo-text {
  font-size: 36rpx;
}

拓展

另外,在使用过程中,可能还存在这些东西

shell 转义

\表示,比如:

\'   \"   \*   \?   \\   \~   \`   \!   \#   \$   \&    \|

特殊实例:
在一对引号中不允许出现单引号,转义字符也不行

比如:echo ‘it is wolf’s book’

这个时候尽可能用双引号替换:echo “it is wolf’s book”

特定的转义符的特殊的含义

echosed命令中使用

\n
表示新的一行

\r
表示回车

\t
表示水平制表符

\v
表示垂直制表符

\b
表示后退符

\a
表示"alert"(蜂鸣或者闪烁)

\"
表示引号字面的意思
echo "Hello"                  # Hello
echo "\"Hello\", he said."    # "Hello", he said.

\$
表示$本身子面的含义(跟在\$后边的变量名将不能引用变量的值)
比如: echo "\$variable01"  # 结果是$variable01

\\
表示反斜线字面的意思
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值