Home > Back-end >  sed replace gives input caret instead of result
sed replace gives input caret instead of result

Time:01-21

I want to exchange an unknown hash to a known one in a file. Lot's of escaping needed...

An example for the line to replace:

define( 'PB_PASSWORD', 'ab57a5449b0781c91c4701ab6258655d' );

The target might be:

define( 'PB_PASSWORD', '438bb1dc13ec5cbdf3b938e4fc6c3748' );

This should be done in a linux shell script. I got this far with sed:

sed -i 's/define\( \'PB_PASSWORD\', \'[^“]*\' \);/define\( \'PB_PASSWORD\', \'438bb1dc13ec5cbdf3b938e4fc6c3748\' \);/' todo.txt

But all this does is give me an input

>

I tried several ways to achieve this and I think it's the escaping that keeps me from reaching my goal.

What am I doing wrong?

CodePudding user response:

You can use

sed "s/\(define( 'PB_PASSWORD', '\)[^']*/\1438bb1dc13ec5cbdf3b938e4fc6c3748/"

See the online demo.

Here, the POSIX BRE pattern is used:

  • \(define( 'PB_PASSWORD', '\) - Group 1 (\1 refers to this value from the RHS): the literal define( 'PB_PASSWORD', ' text
  • [^']* - any zero or more chars other than '.

Note it is fine to use a digit right after \1 as you can only define up to 9 group backreferences in a POSIX regex flavor.

In your environment, you can use

sed -i "s/\(define( 'PB_PASSWORD', '\)[^']*/\1438bb1dc13ec5cbdf3b938e4fc6c3748/" todo.txt
  • Related