Combining echo and cat on Unix
Asked Answered
N

6

44

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.

Nicobarese answered 9/6, 2010 at 11:44 Comment(0)
C
50

This should work:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
Charnel answered 9/6, 2010 at 11:47 Comment(6)
I like this simplicity, but for completeness should have the -n flag on echo as mentionned in another answer.Nicobarese
For anyone else wondering about the - in the cat args, from the man pages: With no FILE, or when FILE is -, read standard input.Bibliotaph
The -n flag doesn't work on all variants of echo, but that is mostly a historical note.Dianthus
I've always been using { echo "PREPENDED STRING"; cat /tmp/file; } | but this is much more elegant, thank you!Dianthus
Where the -n flag on echo is needed to suppress the trailing newline.Scriptural
Note that the -n must come before the string: echo -n "mystring" | cat - astrophyReckon
E
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.

Educt answered 9/6, 2010 at 11:47 Comment(0)
P
2

Or just use only sed

  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result
Penknife answered 9/6, 2010 at 11:55 Comment(3)
for "one-liner-ness" use 2 -e's: sed -e 's/test/test2/g' -e 's/^/PREPEND STRING/' ...Pilpul
This of course will prepend the string to every line of the input file.Pilpul
Which may be what's wanted. If not: sed '1s/^/PREPENDED STRING/; s/test/test2/g' /tmp/file > /tmp/resultPerennate
B
2

Or also:

{ echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result
Brok answered 9/6, 2010 at 13:12 Comment(1)
Useless use of cat, e.g. this would also work: { echo "PREPENDED STRING" ; sed 's/test/test2/g'; } < /tmp/file > /tmp/resultDianthus
O
1

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.

Otherness answered 26/4, 2013 at 8:1 Comment(0)
P
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
Pilpul answered 9/6, 2010 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.