hobbes3
hobbes3

Reputation: 30208

Multiple replacement in sed

Is there a way to replace multiple captured groups and replace it with the value of the captured groups from a key-value format (delimited by =) in sed?

Sorry, that question is confusing so here is an example

What I have:

aaa="src is $src$ user is $user$!" src="over there" user="jason"

What I want in the end:

aaa="src is over there user is jason!"

I don't want to hardcode the position of the $var$ because they could change.

Upvotes: 1

Views: 219

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed ':again
s/\$\([[:alnum:]]\{1,\}\)\$\(.*\) \1="\([^"]*\)"/\3\2/g
t again
' YourFile

As you see, sed is absolut not interesting doing this kind of task ... even with element on several line it can work with few modification and it doesn not need a quick a dirty 6 complex line of higher powerfull languages.

principe:

  1. create a label (for a futur goto)
  2. search an occurence of a patterne between $ $ and take his associate content and replace pattern with it and following string but without the pattern content definition
  3. if it occur, try once again by restarting at the label reference of the script. If not print and treat next line

Upvotes: 1

Birei
Birei

Reputation: 36252

This is a quick & dirty way to solve it using . It could fail in some ways (spaces, escapes double quotes, ...), but it would get the job done for most simple cases:

perl -ne '
    ## Get each key and value.
    @captures = m/(\S+)=("[^"]+")/g;

    ## Extract first two elements as in the original string.
    $output = join q|=|, splice @captures, 0, 2;

    ## Use a hash for a better look-up, and remove double quotes
    ## from values.
    %replacements = @captures;
    %replacements = map { $_ => substr $replacements{$_}, 1, -1 } keys %replacements;

    ## Use a regex to look-up into the hash for the replacements strings.
    $output =~ s/\$([^\$]+)\$/$replacements{$1}/g;

    printf qq|%s\n|, $output;
' infile

It yields:

aaa="src is over there user is jason!"

Upvotes: 1

Related Questions