Linux sed
目录
sed
sed 多个点进行编译
sed 去除空格
sed 尾部和头部添加字符
sed
sed利用脚本的指令编辑文件
sed语法
sed [OPTION]... {script-only-if-no-other-script} [input-file]...
OPTION:
-e <script> or --expression=<script> 以指定的script来处理文件
-f <script file> or --file=<script file> 以指定的script file来处理文件
-n or --quiet or --silent 仅显示script处理后的结果
-i 直接修改文件内容(原文件被修改)
动作(script):
a 新增 后面可以接字符串,表示在当前的下一行增加一行字符串
nl test.sh | sed '2a hello world'
说明:在test.sh中的第二行下面添加一行"hello world",hollo world 变为第三行
i 插入,后面可以接字符串,表示在当前的上一行新增一行字符串
nl test.sh | sed '2i hello world'
description:在test.sh中的第二行上面添加一行"hello world", "hello world"变为第二行
c 替代,后面可以接字符串,表示替代n1,n2之间的内容
nl test.sh | sed '1,3c delete 1~3 row content'
说明: 替代test.sh中1~3的内容改为"delete 1~3 row content"
d 删除,后面不接任何东西,
nl test.sh | sed '1,3d'
说明:删除test.sh的1~3行(其中包括1和3)
p 打印,前面可以有字符串,表示搜索字符串
nl test.sh | sed -n '/password/p'
打印包含有password的行
s 取代,取代n1,n2行中的某些字符,可以跟正则表达式
nl test.sh | sed ''10s/no/yes/g''
表示"yes"替代test.sh第10行中的"no"
note: 文件中从开头为第一行,其中空格也算作时一行。
多个点进行编辑
sed -i -e '6,7d' -e '10s/no/yes/g' /home/ikvmgt/sshd_config
description:
删除第6,7行,把第10行的no该为yes
sed 去除空格
example:
txt=" hello world "
1. 删除前、后空格,不删除中间空格
sed -e 's/^[ \t]*//g' -e 's/[ \t]*$//g'
2. 去掉尾巴的空格
sed 's/[ \t]*$//g'
3. 删除字符串中所有空格
sed 's/[[:space:]]//g'
sed 尾部和头部添加字符
文件内容
#!/usr/bin/python3 print("hello world")
尾部(第一行的尾部)
sed "1s/$/&$str/g" test.py
开头
sed "1s/^/$str/g" test.py