I have a file that includes a relative path in angle brackets, such as the following (example.txt):
Some content containing <../another.txt> file
Then in the parent directory, the file another.txt:
another
What linux command line can I use to generate example_processed.txt that replaces <path> tokens with the contents of the file at the specified path? E.g., I want a command that ingests example.txt and generates example_processed.txt with the following contents:
Some content containing another file
Note that I don't care if there are extraneous newlines in the generated file, so the following output would also be acceptable (this is just an example, any extraneous whitespace is acceptable):
Some content containing
another
file
I have a bash loop that enables reading in the contents of the file into variables, but again, don't know if this helps me to perform the substitution:
cp example.txt example_processed.txt
grep -oP '<\K.*(?=>)' example.txt | while read -r REPL_PATH ; do
local CONTENTS=$(<"$REPL_PATH")
# TODO: How do I use this? The following is what I want to work:
# sed "s/<$REPL_PATH>/$CONTENTS/g"
echo "$REPL_PATH: $CONTENTS"
done
This is what has produced the closest result, but requires another.txt to be in the same directory:
sed -e '/<\(.*\)>/{' -e 's/<.*>//' -e 'r another.txt' -e '}' -i example.txt
The above outputs:
Some content containing file
another
Questions:
- How can I specify the replacement path as ../another.txt?
- How can I replace the literal another.txt in the above command with the result of capture group #1? E.g.,
sed -e '/<\(.*\)>/{' -e 's/<.*>//' -e 'r \1' -e '}' -i example.txt - How do I move the replacement string between the words "containing" and "file", rather than after the word "file"?
sedcommand that gets close. I didn't include it originally because I don't even know that that is the correct tool, and I didn't want to elicit answers that make assumptions about the tooling. If someone can give me a hint at the correct tool(s) to use, I can investigate myself. Its hard to form a question when I know nothing about where the answer will take me. I also have agrep/loop combination that reads the contents of the file into an environment variable, but then I don't know how to use the variables to perform the substitution. Again, not sure if that helps.