在Unix上结合echo和cat

在Unix上结合echo和cat,unix,shell,piping,Unix,Shell,Piping,非常简单的问题,如何将echo和cat结合在shell中,我试图用一个带前缀的字符串将一个文件的内容写入另一个文件中 如果/tmp/file如下所示: this is a test PREPENDED STRINGthis is a test2 我想运行以下命令: echo "PREPENDED STRING" cat /tmp/file | sed 's/test/test2/g' > /tmp/result 因此/tmp/result如下所示: this is a test

非常简单的问题,如何将echo和cat结合在shell中,我试图用一个带前缀的字符串将一个文件的内容写入另一个文件中

如果/tmp/file如下所示:

this is a test
PREPENDED STRINGthis is a test2
我想运行以下命令:

echo "PREPENDED STRING"
cat /tmp/file | sed 's/test/test2/g' > /tmp/result 
因此/tmp/result如下所示:

this is a test
PREPENDED STRINGthis is a test2
谢谢。

这应该可以:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
尝试:

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

或仅使用sed

  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result
或者:

{ echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result

另一个选项:假设前置字符串只出现一次,而不是每行出现一次:

gawk 'BEGIN {printf("%s","PREPEND STRING")} {gsub(/test/, "&2")} 1' in > out

如果这用于发送电子邮件,请记住使用CRLF行结尾,如下所示:

echo -e 'To: cookimonster@kibo.org\r' | cat - body-of-message \
| sed 's/test/test2/g' | sendmail -t
请注意字符串中的-e-标志和\r


设置为:循环中的这种方式为您提供了世界上最简单的批量邮件程序。

我喜欢这种简单性,但为了完整性,应在echo上设置-n标志,如另一个答案中所述。对于任何想知道
cat
参数中
-
的人,请从手册页中选择:
没有文件,或者当文件为-,阅读标准输入。
-n标志并不适用于
echo
的所有变体,但这主要是一个历史记录。我一直使用
{echo“prepend STRING”;cat/tmp/file;}
,但这更优雅,谢谢!如果需要echo上的-n标志来抑制尾随换行符。对于“一行性”,使用2
-e
's:
sed-e's/test/test2/g'-e's/^/PREPEND STRING/”…
这当然会将字符串前置到输入文件的每一行。这可能是需要的。如果不是:
sed'1s/^/前置字符串/;s/test/test2/g'/tmp/file>/tmp/result
无用地使用
cat
,例如,这也会起作用:
{echo“PREPENDED STRING”;sed's/test/test2/g';}/tmp/result