在Unix上结合echo和cat

Dan*_*Dan 31 unix shell piping

真的很简单的问题,如何在shell中组合echo和cat,我正在尝试将文件的内容写入另一个带有前置字符串的文件中?

如果/ tmp/file看起来像这样:

this is a test
Run Code Online (Sandbox Code Playgroud)

我想运行这个:

echo "PREPENDED STRING"
cat /tmp/file | sed 's/test/test2/g' > /tmp/result 
Run Code Online (Sandbox Code Playgroud)

所以/ tmp/result看起来像这样:

PREPENDED STRINGthis is a test2
Run Code Online (Sandbox Code Playgroud)

谢谢.

Dou*_*las 38

这应该工作:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
Run Code Online (Sandbox Code Playgroud)

  • 对于其他任何想知道`cat` args中`-`的人,从手册页:`没有文件,或文件是 - ,读标准输入. (7认同)
  • 我喜欢这种简单性,但为了完整性,应该在echo中使用-n标志,如另一个答案中所提到的那样. (4认同)
  • `-n`标志不适用于`echo`的所有变体,但这主要是历史记录. (2认同)
  • 我一直在使用``echo"PREPENDED STRING"; cat/tmp/file; } |`但这更优雅,谢谢! (2认同)

Gre*_*ill 11

尝试:

(printf "%s" "PREPENDED STRING"; sed 's/test/test2/g' /tmp/file) >/tmp/result
Run Code Online (Sandbox Code Playgroud)

括号在子shell中运行命令,因此输出看起来像>/tmp/result重定向的单个流.