Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: replacing a substring in pipe stdin

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?

like image 439
rapt Avatar asked Oct 22 '14 21:10

rapt


People also ask

How do I replace text in a string in bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

How do I replace a string with another string in Linux?

Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Can you pipe to sed?

sed can be used with other CLI tools through pipelines. Since sed can read an input stream, CLI tools can pipe data to it. Similarly, since sed writes to stdout, it can pipe its output to other commands.

How do you replace a variable in a string in Shell?

To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.


2 Answers

You can use the command sed.

cat file1 file2 | sed -e 's/@path_to_file/path/to/file/' ...
like image 87
Denis Kohl Avatar answered Oct 04 '22 15:10

Denis Kohl


With Parameter Expansion:

cat file1 file2 | while read -r line; do echo "${line/@path_to_file/path\/to\/file}"; done
like image 33
Cyrus Avatar answered Oct 04 '22 16:10

Cyrus