43

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.

Dan
  • 33,953
  • 24
  • 61
  • 87

6 Answers6

50

This should work:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
Douglas
  • 36,802
  • 9
  • 76
  • 89
11

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.

pixelbeat
  • 30,615
  • 9
  • 51
  • 60
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

Or just use only sed

  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result
Iacopo
  • 4,224
  • 1
  • 23
  • 25
2

Or also:

{ echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result
mathk
  • 7,973
  • 6
  • 45
  • 74
  • 1
    Useless use of `cat`, e.g. this would also work: `{ echo "PREPENDED STRING" ; sed 's/test/test2/g'; } < /tmp/file > /tmp/result` – reinierpost Apr 26 '13 at 08:08
1

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.

kaleissin
  • 1,245
  • 13
  • 19
0

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352