sed在指定行上删除和添加字符

欢迎转载!转载时请注明出处:http://blog.csdn.net/nfer_zhuang/article/details/44020599

引言

我在一个项目中需要发布版本,两个客户的需求基本相同,只有是在一个fm34(消回音)模块上一个有该功能,另外一个没有。那么就存在在发版本的时候根据需要打开和关闭关于fm34相关的代码。

其中的一个就是是否需要inmod一个ko文件,我的处理是:

  • 在脚本中有inmod该ko的一行代码,但是默认是被注释掉的
  • 在给需要该功能的客户发布版本时,通过sed将改行的注释去掉(shell中的#字符)
  • 编译出带有fm34功能的版本
  • 发布版本完成后,记得将该行在注释回去(有可能在给另外一个客户发版本)

在这里,我就需要如何在脚本中自动完成上面的操作,先给出最终的脚本代码:

#!/bin/bash

# enable snd-soc-wmt-fm34
sed -i '/snd-soc-wmt-fm34/s/^#//' fs_patch/load_drivers.sh

source release_Common.sh

# disable snd-soc-wmt-fm34 back
sed -i '/snd-soc-wmt-fm34/s/^/#&/' fs_patch/load_drivers.sh

上面的代码主要是包括一下几个步骤:

  1. 删除行首的#字符,打开注释部分代码
  2. 编译版本
  3. 将指定行代码再次注释起来

sed行首删除一个字符

sed -i '/snd-soc-wmt-fm34/s/^#//' fs_patch/load_drivers.sh

-i表示在原始文件上进行修改。

       -i[SUFFIX], --in-place[=SUFFIX]
              edit files in place (makes backup if extension supplied)

s/^#//表示将字符串开头的#字符替换为空(即去除行首的#字符)

       s/regexp/replacement/
              Attempt  to  match  regexp  against  the  pattern  space.  If successful, replace that portion matched with replacement.  The replacement may contain the special character & to refer to that portion of  the  pattern space  which  matched,  and  the  special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

其中s/regexp/replacement/命令支持address ranges,在该脚本中使用的是正则表达式匹配确定address ranges的方式:

/snd-soc-wmt-fm34/表示匹配含有snd-soc-wmt-fm34字符串的行

       /regexp/
              Match lines matching the regular expression regexp.

除了使用/regexp/的方式匹配特定行,sed还支持直接指定行号的方式进行操作,则上面的脚本也可以使用采用下面的方式完成:

sed -i '49s/^#//' fs_patch/load_drivers.sh

       number Match only the specified line number.

注意,上面的数字前后都没有任何的附加字符。

sed行首添加一个字符

sed -i '/snd-soc-wmt-fm34/s/^/#&/' fs_patch/load_drivers.sh

注意,这里和上面的删除操作唯一的不同就在于s/^/#&/部分。其中,^字符匹配行首,#字符是一般字符表示添加该字符,&字符是我们这里需要重点关心的。在上面的关于s/regexp/replacement/命令描述时有以下字段:

The replacement may contain the special character & to refer to that portion of  the  pattern space  which  matched,  and  the  special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

这里提到了两种特殊字符:

&:refer to that portion of  the  pattern space  which  matched,即表示前面的正则表达式匹配出来的部分,而在这里指的就是行首位置。实际上,在此处我们完全可以不要&字符,也是可以完成任务的。

\1...\9:refer to the corresponding matching sub-expressions in the regexp,主要用于多匹配时(如匹配行中的特定位置)分别表示前面的正则表达式匹配出来的部分,这里的多匹配需要使用()来进行分割,如上面的代码可以分别使用下面两种方式进行实现:

sed -i '/snd-soc-wmt-fm34/s/\(^\)/\1#/' fs_patch/load_drivers.sh
sed -i '/snd-soc-wmt-fm34/s/\(^\)\(.*\)/#\2/' fs_patch/load_drivers.sh

具体内容请参考正则表达式相关知识。

其它

本例中是根据工作需要在行首添加和删除字符,如果是在行尾进行操作,则需要使用&通配符;而如果需要在行中的其它位置进行操作,则可能就需要使用到多匹配的方式。

猜你喜欢

转载自blog.csdn.net/nfer_cn/article/details/44020599
今日推荐