String replacement

Hi I am new to shell scripting but i manage to do some simple things.
I am trying to replace a string in one file. I am using sed to replace but it is not permanently writing to the file, rather it is temporary. I want to know whether is there any another method to replace a string in a file permenantly.

THIS IS WHAT I HAVE DONE:

$ cat conf.txt
This is first line which contains NO
This is second line which contains NO
This is thrid line which contains NO

I used sed to replace NO with YES in 2nd line.

$cat -n conf.txt | grep 2 | sed 's/NO/YES/g'

2 This is second line which contains YES

But i want this to happen in the file. I want the replacement to be happened in file(2nd line though).

Please guide me regarding the same and correct me if iam wrong. :frowning:

Thanks in advance.
ss

With awk:

awk 'NR==2{gsub("NO","YES")}1' file

Regards

Thank you very much for the help.

But the file is not getting updated with the change.

Say for example, if the command is run, the file should be changed with the output it produces.

awk 'NR==2{gsub("NO","YES")}1' file > newfile && mv newfile file

Regards

sed -e '2s/NO/YES/' file > newfile && mv newfile file

Thats great its working fine.
I have one more doubt... If i want to change the line number dynamically, ex: using some variable which gets input from user.

awk 'NR=="$i"{gsub("NO","YES")}1' conf.txt

Very sorry if im silly...

Thankf for you help.:slight_smile:

awk -v lin=${userInputLine} 'NR==lin {gsub("NO","YES")}1' conf.txt

Thank you... Its working....
Cheers:)