Bash: replacing a substring in pipe stdin

20,539

Solution 1

You can use the command sed.

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

Solution 2

With Parameter Expansion:

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

Related videos on Youtube

rapt
Author by

rapt

Updated on October 23, 2020

Comments

  • rapt
    rapt over 3 years

    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?

    • Martin Tournoij
      Martin Tournoij over 9 years
      sed? Or did I miss something in your question?
    • Cyrus
      Cyrus over 9 years
      @rapt: IMHO it is not possible to use cat with Parameter Expansion to catch stdin and replace it.
    • rapt
      rapt over 9 years
      @Cyrus why would it be different from any other variable? mockingeye.com/blog/2013/01/22/…
    • Cyrus
      Cyrus over 9 years
      $(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
    Cyrus over 9 years
    Consider: 's|@path_to_file|path/to/file|'