Sunday, July 10, 2022

[SOLVED] To replace the line on which regex found with content of file which name is in regex captured

Issue

How to get content of file which name is obtained by regex, to be inserted by way of replacing that line, within the sed's applied file? e.g. illustration

$ sed -E '/^file:\s*(\S+)/ r"\1"' file.txt

try to have content of file as visible string found following file: to replace the line where regex matches inside the file.txt


Solution

This might work for you (GNU sed):

sed -E '/^file:\s*(\S+).*/{p;s//cat "\1"/e}' file

Print the line matching the regexp and then evaluate the command cat on the first back-reference.

If the matching line is not needed, then a substitution is suffice:

sed -E 's/^file:\s*(\S+).*/cat "\1"/e' file


Answered By - potong
Answer Checked By - Dawn Plyler (WPSolving Volunteer)