LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sed command search and replace (https://www.linuxquestions.org/questions/linux-newbie-8/sed-command-search-and-replace-4175438441/)

zulkifal 11-23-2012 10:04 AM

sed command search and replace
 
I have this problem where I am looking for a string and replacing it but the issue is that my search criteria returns multiple strings and i need to change only one e.g in /etc/sudoers file

#wheel......
#whel...... NO PASSWD

i only want to remove hash from the line that does not end with "NO PASSWD".I tried using line number method but this string seems to have a different line numbering on different systems. Any ideas?
Thanks

steelneck 11-23-2012 10:48 AM

You could pipe the inverted output from grep to sed, like this:

Code:

grep -v "NO PASS" /etc/sudoers | sed 's/#wheel/wheel/'
You may also know that you can use the -i option for sed to write the change to file instantly.

linosaurusroot 11-23-2012 11:27 AM

I'd advise against changing sudoers directly. Always write to a new file such as sudoers.tmp (with correct owner, group and mode) then use
Code:

visudo -c sudoers.tmp
to confirm satisfactory syntax. Finally rename the temp file to sudoers.

zulkifal 11-23-2012 12:04 PM

I agree with you "linosaurusroot".
Thanks "steelneck" for reply but that command doesnt seem to work. lets make it this way:
what is the right command to search for a string:
# %wheel ALL=(ALL) ALL

and replace it with

%wheel ALL=(ALL) ALL

keep in mind that we have a similar string like
# %wheel ALL=(ALL) NOPASSWD: ALL
in the same file
Thanks

linosaurusroot 11-23-2012 12:24 PM

You could cheat by having for each block of rules you are preparing to switch on and off surround them by comments:
Code:

groucho ALL=/bin/false
# begin wheel group all access
%wheel ALL=(ALL) ALL
# end wheel group all access
harpo ALL=/bin/true

wax on
Code:

sed -i '/# begin wheel/,/# end wheel/s/^#%\(.*\)/%\1/'  sudoers.tmp
wax off
Code:

sed -i '/# begin wheel/,/# end wheel/s/^\(%wheel\)/#\1/'  sudoers.tmp

steelneck 11-24-2012 10:19 AM

Quote:

Originally Posted by zulkifal (Post 4835626)
Thanks "steelneck" for reply but that command doesnt seem to work.

Well, in first post you wrote "NO PASSWD" and now it is "NOPASSWD", could that be the root to that my line did not work for you?

As to the question you wrote now:

Code:

sed 's/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/'
That one will not hit the line containing NOPASSWD

zulkifal 11-26-2012 08:19 AM

Thx steelneck , by the way "linosaurusroot" . can you explain what you wrote? bcause i didnt get it.

schneidz 11-26-2012 10:01 AM

this worx for me:
Code:

[schneidz@hyper ~]$ sed s/'# %wheel ALL=(ALL) ALL'/'%wheel ALL=(ALL) ALL'/ sudo.tmp
%wheel ALL=(ALL) ALL


zulkifal 11-26-2012 10:56 AM

Its working now . Thanks everyone


All times are GMT -5. The time now is 04:40 AM.