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?
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.
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.
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.
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.
You can use the command sed.
cat file1 file2 | sed -e 's/@path_to_file/path/to/file/' ...
With Parameter Expansion:
cat file1 file2 | while read -r line; do echo "${line/@path_to_file/path\/to\/file}"; done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With