【问题标题】:Bash: replacing a substring in pipe stdinBash:替换管道标准输入中的子字符串
【发布时间】:2014-10-22 21:10:44
【问题描述】:

我尝试用新的子字符串替换标准输入中的某个子字符串。在读取cat 的几个文件后,我必须从管道中获取标准输入。然后我想把改变的字符串向前推到管道上。

这是我尝试做的:

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

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

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

有什么想法可以做到这一点吗?

【问题讨论】:

  • sed?还是我错过了你的问题?
  • @rapt:恕我直言,不能使用带有参数扩展的cat 来捕获标准输入并替换它。
  • @Cyrus 为什么它会与任何其他变量不同? mockingeye.com/blog/2013/01/22/…
  • $(cat) 从标准输入读取所有内容并写入标准输出。示例:echo 123 | printf "%0.8d" $(cat),printf 本身不是从标准输入读取的。 ${#(cat)/foo/bar} 语法不正确。正确但不是从标准输入读取:${a/foo/bar} 用 $a 中的 bar 替换第一个 foo。见“参数扩展”:man bash.

标签: bash shell pipe stdin


【解决方案1】:

您可以使用命令 sed。

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

【讨论】:

  • 考虑:'s|@path_to_file|path/to/file|'
【解决方案2】:

带参数扩展:

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

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多