Bash:替换管道标准输入中的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26517168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:37:31  来源:igfitidea点击:

Bash: replacing a substring in pipe stdin

bashshellpipestdin

提问by rapt

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.

我尝试用新的子字符串替换 stdin 中的某个子字符串。在通过cat. 然后我想将更改后的字符串向前推到管道中。

Here is what I try to do:

这是我尝试做的:

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

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

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

我尝试用替换子字符串@path_to_file替换子字符串'path/to/file'(周围的引号是替换子字符串的一部分)。

However bash gives me an error message: bad substitution

但是 bash 给了我一条错误消息: bad substitution

Any ideas how I could accomplish this?

任何想法我怎么能做到这一点?

回答by Denis Kohl

You can use the command sed.

您可以使用命令 sed。

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

回答by Cyrus

With Parameter Expansion:

带参数扩展:

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