Bash:在管道stdin中替换子字符串

20
我试图用一个新的子字符串替换stdin中的特定子字符串。我必须从管道中获取stdin,在使用cat读取多个文件后。然后,我想将更改后的字符串推到管道中。
这是我的尝试: cat file1 file2 | echo ${#(cat)/@path_to_file/'path//to//file'} | ... | ... | ... | ... 我试图用替换子字符串'path/to/file'(引号包括在内)替换子字符串@path_to_file
然而,Bash会给我一个错误消息: bad substitution
有什么方法可以解决这个问题吗?

sed?还是我在你的问题中漏掉了什么? - Martin Tournoij
@rapt:在我看来,使用参数扩展的cat无法捕获标准输入并替换它。 - Cyrus
@Cyrus 为什么它会不同于任何其他变量?http://mockingeye.com/blog/2013/01/22/reading-everything-stdin-in-a-bash-script/ - rapt
$(cat) 从标准输入(stdin)读取所有内容,并写入标准输出(stdout)。例如:echo 123 | printf "%0.8d" $(cat),printf本身不从stdin读取。${#(cat)/foo/bar} 是不正确的语法。正确但不从stdin读取的是 ${a/foo/bar},用于将$a中的第一个foo替换为bar。请参见“参数扩展”:man bash - Cyrus
2个回答

31

你可以使用 sed 命令。

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

28
考虑:'s|@path_to_file|path/to/file|' - Cyrus

3

使用参数扩展:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接