wlg
wlg

Reputation: 179

unix command to replace contents in a file

I have a file hello.txt with content:

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

I need replace the value in "this-is-prod-env" : "yes" with no. The output should be "this-is-prod-env" : "no". How can I do it?

Upvotes: 0

Views: 141

Answers (2)

Aditya
Aditya

Reputation: 364

With Perl:

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

-i.old edits the file inline and saves the old version of the file with the .old suffix (a very useful option if you messed something up)

s/yes/no if /-prod-/ substitutes yes for no if the line contains -prod-

Upvotes: 0

William Pursell
William Pursell

Reputation: 212198

$ 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"

The first solution will work with both files, but the 2nd is more idiomatic.

Upvotes: 1

Related Questions