在 Unix 上结合 echo 和 cat

发布于 2024-09-04 17:35:48 字数 359 浏览 2 评论 0原文

非常简单的问题,如何在 shell 中组合 echo 和 cat,我试图将一个文件的内容写入另一个带有前置字符串的文件?

如果 /tmp/file 看起来像这样:

this is a test

我想运行这个:

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

这样 /tmp/result 看起来像这样:

PREPENDED STRINGthis is a test2

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

樱花落人离去 2024-09-11 17:35:48

这应该有效:

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

This should work:

echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result 
甜味拾荒者 2024-09-11 17:35:48

尝试:

(printf "%s" "PREPENDED STRING"; sed 's/test/test2/g' /tmp/file) >/tmp/result

括号在子 shell 内运行命令,以便输出看起来像 >/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.

旧伤还要旧人安 2024-09-11 17:35:48

或者只使用 sed

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

Or just use only sed

  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result
对你再特殊 2024-09-11 17:35:48

或者也可以:

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

Or also:

{ echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result
楠木可依 2024-09-11 17:35:48

如果这是用于发送电子邮件,请记住使用 CRLF 行结尾,如下所示:

echo -e 'To: [email protected]\r' | cat - body-of-message \
| sed 's/test/test2/g' | sendmail -t

注意字符串内的 -e 标志和 \r

设置为:这种循环方式将为您提供世界上最简单的批量邮件程序。

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.

沐歌 2024-09-11 17:35:48

另一种选择:假设前置字符串只应出现一次,而不是每一行:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文