20

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?

rapt
  • 11,810
  • 35
  • 103
  • 145
  • `sed`? Or did I miss something in your question? – Martin Tournoij Oct 22 '14 at 21:11
  • @rapt: IMHO it is not possible to use `cat` with Parameter Expansion to catch stdin and replace it. – Cyrus Oct 22 '14 at 21:29
  • @Cyrus why would it be different from any other variable? http://mockingeye.com/blog/2013/01/22/reading-everything-stdin-in-a-bash-script/ – rapt Oct 22 '14 at 23:21
  • `$(cat)` reads everything from stdin and write to stdout. Example: `echo 123 | printf "%0.8d" $(cat)`, printf itself reads not from stdin. `${#(cat)/foo/bar}` is incorrect syntax. Correct but reads not from stdin: `${a/foo/bar}` to replace first foo by bar in $a. See "Parameter Expansion": `man bash`. – Cyrus Oct 22 '14 at 23:34

2 Answers2

31

You can use the command sed.

cat file1 file2 | sed -e 's/@path_to_file/path/to/file/' ...
Denis Kohl
  • 739
  • 8
  • 13
3

With Parameter Expansion:

cat file1 file2 | while read -r line; do echo "${line/@path_to_file/path\/to\/file}"; done
Cyrus
  • 84,225
  • 14
  • 89
  • 153