2

I'm trying to replace only the first occurrence of a pattern in a file using a perl one liner.

>touch tmp
>perl -p -i.bak -e '++$seen if( !$seen && s/alpha/beta/);' tmp

After this I press Enter. Below message appears on the screen.

perl -p -i.bak -e '++$seen if( tmpseen && s/alpha/beta/);' tmp

Note that !$seen got replaced with tmpseen.

Why is this happening?

Thanks.

3
  • 3
    This is due to csh. !$ is expanding to the last argument of the previous command. I'm assuming that. Commented Mar 27, 2013 at 16:18
  • @kjprice indeed. that seems to be the case. what can I do now? Commented Mar 27, 2013 at 16:21
  • @user13107 I don't use csh, but I'm guessing if( \!$seen will work. Commented Mar 27, 2013 at 16:25

2 Answers 2

4

As kjprice mentioned !$ gets expanded by the shell. One possible solution is to use the operator 'not' instead of the operator !.

perl -p -i.bak -e '++$seen if( (not $seen) && s/alpha/beta/);' tmp

Parentheses are there because of the lower precedence of the operator 'not'

Sign up to request clarification or add additional context in comments.

Comments

3

You can escape any csh special characters with \ :

 perl -p -i.bak -e '++$seen if( \!$seen && s/alpha/beta/);' tmp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.