【问题标题】:Sending text plus the contents of a file to standard input, without using temporary files将文本和文件内容发送到标准输入,而不使用临时文件
【发布时间】:2012-09-06 07:01:55
【问题描述】:

我们知道将文本文件 file.txt 的内容发送到从标准输入读取的脚本很简单:

the_script < file.txt

假设我想做与上面相同的事情,除了我想将额外的一行文本发送到脚本后跟文件的内容?肯定有比这更好的方法:

echo "Here is an extra line of text" > temp1
cat temp1 file.txt > temp2
the_script < temp2

这可以在不创建任何临时文件的情况下完成吗?

【问题讨论】:

  • 您应该为有效的答案投票,而不仅仅是在其下方发表评论

标签: linux unix scripting


【解决方案1】:

以 cdarke 的回答为基础,使其从左到右可读:

echo "Extra line" | cat - file.txt | the_script

【讨论】:

    【解决方案2】:

    有几种方法可以做到这一点。现代 shell(Bash 和 ksh93)具有支持从标准输入读取单个值的功能,称为 here 字符串

    cat - file.txt <<< "Extra line"|the_script
    

    cat 的第一个参数是从标准输入读取的连字符 -。这里的字符串遵循&lt;&lt;&lt; 表示法。

    【讨论】:

      【解决方案3】:

      这应该在bash:

      { echo "Here is an extra line of text"; cat file.txt; } < the_script
      

      【讨论】:

      • 谢谢,效果很好。假设the_script 有一个可选标志,即the_script --option。这如何适合这个例子?
      • 你可以在the_script之后添加标志,像这样:{ echo "Here is an extra line of text"; cat file.txt; } &lt; the_script --option
      猜你喜欢
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2013-11-11
      • 2022-06-17
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多