467,108 Members | 1,282 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,108 developers. It's quick & easy.

Perl inplace search/replace

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


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-)

Oct 3 '08 #1
  • viewed: 5110
3 Replies
Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. perl -i.bak -pe "s/root:\Q$old\E/root:$new/" /etc/master.passwd
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.

Oct 3 '08 #2
Expert Mod 2GB
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.


Oct 3 '08 #3
Expert 2GB
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.

Similar topics

8 posts views Thread by Patio87 | last post: by
77 posts views Thread by Hunn E. Balsiche | last post: by
52 posts views Thread by Olivier Scalbert | last post: by
9 posts views Thread by Xah Lee | last post: by
1 post views Thread by Al Belden | last post: by
reply views Thread by Gabriel Genellina | last post: by
223 posts views Thread by Pilcrow | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.