繁体   English   中英

unix 命令替换文件中的内容

[英]unix command to replace contents in a file

我有一个内容为hello.txt的文件:

"this-is-prod-env" : "yes"
"this-is-devl-env" : "yes" 

我需要用no替换"this-is-prod-env": "yes"中的值。 output 应该是"this-is-prod-env": "no" 我该怎么做?

$ cat input
 "this-is-prod-env" : "yes" "this-is-devl-env" : "yes"
$ sed -E 's/("this-is-prod-env" *: )"yes"/\1"no"/' input
 "this-is-prod-env" : "no" "this-is-devl-env" : "yes"
$ cat input2
 "this-is-prod-env" : "yes"
 "this-is-devl-env" : "yes"
$ sed '/this-is-prod-env/s/yes/no/' input2
 "this-is-prod-env" : "no"
 "this-is-devl-env" : "yes"

第一个解决方案适用于这两个文件,但第二个更惯用。

使用 Perl:

perl -i.old -pe 's/yes/no/ if /-prod-/' hello.txt

-i.old内联编辑文件并使用.old后缀保存文件的旧版本(如果您搞砸了,这是一个非常有用的选项)

s/yes/no if /-prod-/如果该行包含-prod- ,则用yes代替no

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM