2010-06-09 71 views
26

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

如果/ tmp目录/文件看起来像这样:

this is a test 

我想运行此:

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

,这样的/ tmp /结果是这样的:

PREPENDED STRINGthis is a test2 

谢谢。

回答

30

这应该工作:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
+3

我喜欢这种简单性,但为了完整起见,在回声中应该有-n标志,正如另一个答案中提到的那样。 – Dan 2010-06-09 12:10:47

+6

对于那些对'cat'参数中的'-'感兴趣的人,从手册页:'没有FILE,或者当FILE是 - 时,读取标准输入。' – SooDesuNe 2012-01-13 14:33:54

+2

'-n'标志不起作用“echo”的所有变体,但那大多是历史记录。 – reinierpost 2013-04-26 08:05:20

11

尝试:

(printf "%s" "PREPENDED STRING"; sed 's/test/test2/g' /tmp/file) >/tmp/result 

的括号中的子shell中运行的命令(S),从而使输出看起来像为>/tmp/result重定向一个流。

2

或者仅仅只使用sed的

sed -e 's/test/test2/g 
s/^/PREPEND STRING/' /tmp/file > /tmp/result 
+0

for“one-liner-ness”use 2'-e''s:'sed -e's/test/test2/g'-e's/^/PREPEND STRING /'...' – 2010-06-09 13:45:58

+0

这当然将在输入文件的每一行预先添加字符串。 – 2010-06-09 13:55:22

+0

这可能是想要的。如果不是:'sed'1s/^/PREPENDED STRING /; s/test/test2/g'/ tmp/file>/tmp/result' – 2010-06-09 14:18:07

0

或者也:

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

无用的'cat',例如这也将起作用:'{echo“PREPENDED STRING”; sed's/test/test2/g'; } < /tmp/file >/tmp/result' – reinierpost 2013-04-26 08:08:14

0

另一个选择:假设预谋串只应出现一次,而不是每行:

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

如果要发送电子邮件,请记住使用CRLF行结束符,如下所示:

echo -e 'To: [email protected]\r' | cat - body-of-message \ 
| sed 's/test/test2/g' | sendmail -t 

通知的-e -flag和\ r里面的字符串。

设置为:以循环方式提供世界上最简单的批量邮件。