简体   繁体   中英

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.

这应该工作:

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

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.

或者:

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

另一种选择:假设前置字符串应该只显示一次而不是每一行:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM