2010-06-09 73 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裏面的字符串。

設置爲:以循環方式提供世界上最簡單的批量郵件。