2

I have a file ~/foo.txt that has instances of each of the following strings

alpha-1
alpha-2
alpha-3
alpha-4
alpha-5
alpha-6
alpha-7
alpha-8
alpha-9

I would like to replace each of these alpha-X with beta-X. Simply replacing alpha- with beta- will not suffice as there are other instances of alpha- that I want to preserve.

I imagine this can be accomplished with something like

perl -p -i -e `s/alpha-SOMETHING/beta-SOMETHING/g'

but I'm not sure what SOMETHING should be. Is there a solution here?

(Of course, I could run nine one-liners but this seems very inefficient.)

  • 1
    Replace SOMETHING like s/alpha(-[[:digit:]])\b/beta$1/g – Costas Jan 15 '16 at 22:47
  • @brian, you will have to be painfully explicit: which alphas should be replaced and which should be kept? – glenn jackman Jan 16 '16 at 1:30
  • @Costas, perl offers the shorthand \d for [[:digit:]] – glenn jackman Jan 16 '16 at 1:31
  • I don't see 0 in the list, so [1-9] might be appropriate here. – BowlOfRed Jan 16 '16 at 2:32
  • Note, that you're first quote is not correct. – pLumo May 15 '19 at 14:05
1
perl -p -i -e 's/alpha-(\d)/beta-$1/g'
  • \d matches 0...9
  • (\d) captures (saves) what was matched and assigns it to the $1 variable (if you add another capture it would be assigned to the next variable $2)
  • if the number can have more than one digit you can use \d+ to match one-or-more digits.
1

This is the perfect use-case for a lookahead:

's/alpha(?=-\d)/beta/'

This will replace alpha with beta only if it is followed by -\d.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.