我需要:
从管道接受脚本中的 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/