By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,933 Members | 1,675 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,933 IT Pros & Developers. It's quick & easy.

Perl inplace search/replace

P: 1
I am trying to edit a file in place.....it is the /etc/master.passwd in OSX I need to push out a script that adds a crypt password for root. The file by default has an * so the line starts with

root:*:blah blah blah

I can read that in using cat and awk and define the old variable, and I can define the new variable using htpasswd but when I try the search and replace I can't get rid of the darn *...I would guess it has something to do with * being an expression...and not being treated as just plain text...

perl -p -i -e "s/root\:$old/root\:$new/"

so it SHOULD replace root:* with root:WUfjdLeuIJfhE

or whatever....but what I get is

root:WUfjdLeuIJfhE*

So the * hangs in there. Also....if the * is not there, I can read and replace that value with the same script with no issues. I was hoping NOT to have to branch into an IF statement and do it all with a nice one liner....here it is...

new=`htpasswd -nb root test | awk -F: '/root/ {print $2}'`; old=`cat /etc/master.passwd | awk -F: '/root/ {print $2}'`; perl -p -i -e "s/root\:$old/root\:$new/" /etc/master.passwd

That SHOULD work and like I said in my testing anything but root:* works

It's driving me mad.....please help....8-)

-Mike
Oct 3 '08 #1
Share this Question
Share on Google+
3 Replies


nithinpes
Expert 100+
P: 410
Use:
Expand|Select|Wrap|Line Numbers
  1. perl -i.bak -pe "s/root:\Q$old\E/root:$new/" /etc/master.passwd
  2.  
The \Q and \E options will remove any special meaning of the pattern enclosed within them. So, "*" will be treated just as a character instead as a quantifier.

-Nithin
Oct 3 '08 #2

numberwhun
Expert Mod 2.5K+
P: 3,503
Just a quick bit of curiosity here....

What version of OSx are you running? I am no expert on OSx, but according to this article, if you are on 10.3 or above, then the password file is shadowed, as it is with most Unix's today. The article also does not make mention of a master.passwd file, so I don't know its true purpose.

Regards,

Jeff
Oct 3 '08 #3

KevinADC
Expert 2.5K+
P: 4,059
Expand|Select|Wrap|Line Numbers
  1. new=`htpasswd -nb root test | awk -F: '/root/ {print $2}'`;
  2. old=`cat /etc/master.passwd | awk -F: '/root/ {print $2}'`;
  3. perl -p -i -e "s/root\:$old/root\:$new/" /etc/master.passwd
Does that work besides the problem of the "*"? It looks like $old and $new might not be interpolated correctly by perl.
Oct 3 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.