tags:

views:

80

answers:

5

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.

+1  A: 

This should work:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
Douglas
I like this simplicity, but for completeness should have the -n flag on echo as mentionned in another answer.
Dan
+4  A: 

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.

Greg Hewgill
+2  A: 

Or just use only sed

  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result
Iacopo
for "one-liner-ness" use 2 `-e`'s: `sed -e 's/test/test2/g' -e 's/^/PREPEND STRING/' ...`
glenn jackman
This of course will prepend the string to every line of the input file.
glenn jackman
Which may be what's wanted. If not: `sed '1s/^/PREPENDED STRING/; s/test/test2/g' /tmp/file > /tmp/result`
Dennis Williamson
A: 

Or also:

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

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