shell脚本修改文本中匹配行之前的行的方法

Posted 飞翔雨feixy的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell脚本修改文本中匹配行之前的行的方法相关的知识,希望对你有一定的参考价值。

原创文件,欢迎阅读,禁止转载。

例子中是把 finish 前一行的 "yes" 改成 "YES"
有一个方法就是利用sed+awk一起来完成。

[email protected]:~$ cat a.txt
line 0 is yes
line 1 is yes
line 2 is yes
line 3 is yes
finish line
this line is no
this line is no
#//用awk找到匹配行号算出要修改的行
[email protected]:~$ awk /finish/{print NR-1} a.txt
4
#//用sed修改这行
[email protected]:~$ sed "4 s/yes/YES/" a.txt
line 0 is yes
line 1 is yes
line 2 is yes
line 3 is YES
finish line
this line is no
this line is no

这有什么实际用处呢?比如我要在某启动脚本的exit前就两行代码,就需要这么做。

原创文件,欢迎阅读,禁止转载。


以上是关于shell脚本修改文本中匹配行之前的行的方法的主要内容,如果未能解决你的问题,请参考以下文章

Shell脚本

Shell脚本中计算字符串长度的5种方法及从文本获取某一行

文本处理工具和正则表达式SHELL脚本编程

shell脚本--sed的用法

bash shell脚本,如何用sed 命令打印出匹配行和匹配行的第N行

shell脚本四剑客--sed的应用