Bash: replacing a substring in pipe stdin

2019-06-22 05:45发布

问题:

I try to replace a certain substring from the stdin with a new substring. I have to get the stdin from the pipe, after reading several files by cat. Then I want to push the changed string forward to the pipe.

Here is what I try to do:

cat file1 file2 | echo ${#(cat)/@path_to_file/'path//to//file'} | ... | ... | ... | ...

I try to replace the substring @path_to_file with the replacement substring 'path/to/file' (the surrounding quotes are part of the replacement substring).

However bash gives me an error message: bad substitution

Any ideas how I could accomplish this?

回答1:

You can use the command sed.

cat file1 file2 | sed -e 's/@path_to_file/path/to/file/' ...


回答2:

With Parameter Expansion:

cat file1 file2 | while read -r line; do echo "${line/@path_to_file/path\/to\/file}"; done