Sed insert back reference into command -


can use matched group sed command, command, generates replacement. that:

sed -e 's/\(<regex>\)/$(<command using \1 reference , generating replacement>)/g' 

i need replacement in first file, according file contents (replacement not constant , based on concrete replaced line).

as @etanreisner mentions, possible gnu sed -- , still tricky. also, potentially dangerous, , should use if input comes trustworthy source.

anyway, e modifier s/// command treats contents of pattern space after substitution made shell command, runs it, , replaces pattern space output of command, means output have shunted place manually. general pattern is

sed '/regex/ { h; s//\n/; x; s//\n&\n/; s/.*\n\(.*\)\n.*/command \1/e; x; g; s/\([^\n]*\)\n\([^\n]*\)\n\(.*\)/\1\3\2/ }' filename 

let's go through top:

/regex/ {                                  # when find seek:    h                                        # make copy of current line in                                            # hold buffer.    s//\n/                                   # put newline match occurs                                            # (// reattempts last attempted                                            # regex, 1                                            # start). serves marker                                            # output of command                                            # inserted.    x                                        # swap copy in; marked                                            # line moves hold buffer    s//\n&\n/                                # put markers around match                                            # time,    s/.*\n\(.*\)\n.*/command \1/e            # use markers construct                                            # command , run it. pattern                                            # space contains output of                                            # command now.    x                                        # swap marked line in    g                                        # append output    s/\([^\n]*\)\n\([^\n]*\)\n\(.*\)/\1\3\2/ # split, reassemble in                                            # right order, using                                            # newline marker put there in                                            # beginning splitting                                            # point. } 

regex , command have replaced regex , command, obviously. can try out with

echo 'foo /tmp/ bar' | sed '/\/\s*/ { h; s//\n/; x; s//\n&\n/; s/.*\n\(.*\)\n.*/ls \1/e; x; g; s/\([^\n]*\)\n\([^\n]*\)\n\(.*\)/\1\3\2/ }' 

this run ls /tmp/ , put listing between foo , bar.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -