Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need to do a search and replace to encapsulate a variable string in single-quotes (php object notation into php array notation) such that the following block:

$my_trip->trip_id = ( $my_trips_opts->trip_id > 0 ) ? $my_trips_opts->trip_id : 1;
$my_trip->trip_name = $my_trips_opts->trip_name;
$my_trip->trip_location_paris = ( $my_trips_opts->trip_location_paris == 'paris' || $my_trips_opts->trip_location_paris == true ) ? true : false;

Is converted to:

$my_trip->trip_id = ( $my_trips_opts['trip_id'] > 0 ) ? $my_trips_opts['trip_id'] : 1;
$my_trip->trip_name = $my_trips_opts['trip_name'];
$my_trip->trip_location_paris = ( $my_trips_opts['trip_location_paris'] == 'paris' || $my_trips_opts['trip_location_paris'] == true ) ? true : false;

The challenge is that the string that follows "$my_trip_opts->" is variable, and likely needs to be stored in a buffer.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Not buffers: what you need are tagged regular expressions.

sed "s/\(\$my_trips_opts\)->\([a-zA-Z_]*\>\)/\1['\2']/g"

Basically, in s/patterns/replacement/, if you enclose patterns in escaped brackets, you can refer to them in the replacement by \1, \2 and so on.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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