linux - 从 STDIN 读取,执行命令,然后在 Bash 中输出到 STDOUT

标签 linux bash shell sed

我需要:

  • 从管道接受脚本中的 STDIN

  • 将其保存到临时文件,这样我就不会修改原始源

  • 对临时文件执行操作以生成一些输出

  • 输出到 STDOUT

这是我的脚本:

#!/bin/bash

temp=$(cat)

sed 's/the/THE/g' <temp

echo "$temp"

现在,我只是想让它能够用“THE”替换所有出现的“the”。

这里是示例文本:

the quick brown fox jumped over the lazy

brown dog the quick

brown fox jumped

over

这是我的命令行:

cat test.txt | ./hwscript >hwscriptout

“test.txt”包含示例文本,“hwscript”是脚本,“hwscriptout”是输出

但是,当我查看输出文件时,没有任何变化(所有出现的“the”都保持大写)。当我在命令行而不是脚本上执行 sed 命令时,它可以工作。我还尝试使用 $(sed) 而不是 sed,但当我这样做时,命令返回错误:

“./hwscript:第5行:s/the/THE/g:没有这样的文件或目录”

我尝试寻找解决方案,但找不到。

非常感谢您的帮助,谢谢。

最佳答案

save it to a temp file so that I don't modify the original source

通过 stdin 接收到的任何内容都只是一个数据流,与它的来源无关:无论您对该流做什么都不会对其来源产生任何影响

因此,不需要涉及临时文件 - 只需根据需要修改 stdin 输入

#!/bin/bash

sed 's/the/THE/g'  # without a filename operand or pipe input, this will read from stdin
# Without an output redirection, the output will go to stdout.

正如您所知,在这个简单的情况下,您也可以直接使用 sed 命令,而无需创建脚本。

关于linux - 从 STDIN 读取,执行命令,然后在 Bash 中输出到 STDOUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29572961/

相关文章:

linux - 为什么 QProcess 不 kill,close,terminate 调用进程的析构函数?

linux - 如果找到第一个字符为 "<"的行,则打印第一个字符为 ">"的行的第一次出现

bash - 在bash中将文件转换为二维数组

linux - perl $ENV 没有得到 linux bash var 的值

linux - 在服务器部署中使用 shell 生成随 secret 码

linux - 嵌入式设备为何以及何时会同时具有 NAND 和 NOR?

javascript - jQuery:还有另一种解决方案吗?

python - Mac 默认 Python 路径更改

linux - 将 std 错误重定向到文件时的顺序为 2>&1

python - 从一个 csv 文件中的数据创建多个 csv 文件