从 STDIN 读取,执行命令,然后在 Bash 中输出到 STDOUT
Reading from STDIN, performing commands, then Outputting to STDOUT in Bash
我需要:
通过管道在我的脚本中接受 STDIN
将它保存到一个临时文件中,这样我就不会修改原始源
对临时文件执行操作以生成一些输出
输出到标准输出
这是我的脚本:
#!/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: 没有那个文件或目录"
我曾尝试寻找解决方案,但找不到。
感谢帮助,谢谢。
使用这个:
temp=$(sed 's/the/THE/' <<<"$temp")
或
temp=$(printf "%s" "$temp" | sed 's/the/THE/')
您告诉 sed
处理名为 temp
的文件,而不是变量 $temp
的内容。您也没有在任何地方保存结果,所以 echo "$temp"
只是打印旧值
这是您描述的一种方法
#!/bin/sh
# Read the input and append to tmp file
while read LINE; do
echo ${LINE} >> yourtmpfile
done
# Edit the file in place
sed -i '' 's/the/THE/g' yourtmpfile
#Output the result
cat yourtmpfile
rm yourtmpfile
这里有一个没有 tmp 文件的更简单的方法
#!/bin/sh
# Read the input and output the line after sed
while read LINE; do
echo ${LINE} | sed 's/the/THE/g'
done
save it to a temp file so that I don't modify the original source
通过 stdin
收到的任何东西都只是一个 数据流 ,与它的来源断开连接:无论你用那个流做什么 no对其起源有任何影响.
因此,不需要涉及临时文件 - 只需根据需要修改 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
命令,而无需创建脚本。
我需要:
通过管道在我的脚本中接受 STDIN
将它保存到一个临时文件中,这样我就不会修改原始源
对临时文件执行操作以生成一些输出
输出到标准输出
这是我的脚本:
#!/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: 没有那个文件或目录"
我曾尝试寻找解决方案,但找不到。
感谢帮助,谢谢。
使用这个:
temp=$(sed 's/the/THE/' <<<"$temp")
或
temp=$(printf "%s" "$temp" | sed 's/the/THE/')
您告诉 sed
处理名为 temp
的文件,而不是变量 $temp
的内容。您也没有在任何地方保存结果,所以 echo "$temp"
只是打印旧值
这是您描述的一种方法
#!/bin/sh
# Read the input and append to tmp file
while read LINE; do
echo ${LINE} >> yourtmpfile
done
# Edit the file in place
sed -i '' 's/the/THE/g' yourtmpfile
#Output the result
cat yourtmpfile
rm yourtmpfile
这里有一个没有 tmp 文件的更简单的方法
#!/bin/sh
# Read the input and output the line after sed
while read LINE; do
echo ${LINE} | sed 's/the/THE/g'
done
save it to a temp file so that I don't modify the original source
通过 stdin
收到的任何东西都只是一个 数据流 ,与它的来源断开连接:无论你用那个流做什么 no对其起源有任何影响.
因此,不需要涉及临时文件 - 只需根据需要修改 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
命令,而无需创建脚本。