Dan
Dan

Reputation: 35433

Combining echo and cat on Unix

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 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.

Upvotes: 45

Views: 55858

Answers (6)

kaleissin
kaleissin

Reputation: 1295

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

echo -e 'To: [email protected]\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.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246764

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

Upvotes: 0

mathk
mathk

Reputation: 8133

Or also:

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

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992887

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.

Upvotes: 11

Douglas
Douglas

Reputation: 37763

This should work:

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

Upvotes: 51

Iacopo
Iacopo

Reputation: 4292

Or just use only sed

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

Upvotes: 2

Related Questions