开发者

Combining echo and cat on Unix

开发者 https://www.devze.com 2023-01-02 16:25 出处:网络
Really simple question, how do I combine echo and cat in the shell, I\'m trying to write the contents of a file into another file with a prepended string?

Really simple question, how do I combine echo and cat in the shell, I'm trying to write the contents of a file into another file with a prepended string?

If /tmp/file looks开发者_StackOverflow社区 like this:

this is a test

I want to run this:

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

so that /tmp/result looks like this:

PREPENDED STRINGthis is a test2

Thanks.


This should work:

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


Try:

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

The parentheses run the command(s) inside a subshell, so that the output looks like a single stream for the >/tmp/result redirect.


Or just use only sed

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


Or also:

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


If this is ever for sending an e-mail, remember to use CRLF line-endings, like so:

echo -e 'To: cookimonster@kibo.org\r' | cat - body-of-message \
| sed 's/test/test2/g' | sendmail -t

Notice the -e-flag and the \r inside the string.

Setting To: this way in a loop gives you the world's simplest bulk-mailer.


Another option: assuming the prepended string should only appear once and not for every line:

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

精彩评论

暂无评论...
验证码 换一张
取 消