【问题标题】:bash command to redirect stdin in while loop (using sed)bash 命令在 while 循环中重定向标准输入(使用 sed)
【发布时间】:2017-11-25 14:41:12
【问题描述】:

我正在尝试仅将文件 (output.txt) 中的第 1 到 1000 行标准输入到 while 循环中。

我尝试过这样的事情:

#!/bin/bash
while read -r line; do
    echo "$line"
done < (sed -n 1,1000p data/output.txt)

【问题讨论】:

  • 明确设置解释器是明智的,因为您在bash 中以#!/bin/bash 或安装在您机器上的任何位置运行它

标签: bash while-loop stdin readfile


【解决方案1】:

刚试过:

#!/bin/bash
while read -r line; do
    echo "$line"
done < <(sed -n 1,1000p data/output.txt)

添加另一个尖括号“

谢谢

【讨论】:

【解决方案2】:

&lt;()部分称为进程替换,它可以替换命令中的文件名。

fifos 也可以用来做同样的事情。

mkfifo myfifo

sed -n 1,1000p data/output.txt > myfifo &

while read -r line; do
    echo "$line"
done < myfifo

【讨论】:

    【解决方案3】:

    您似乎想将输出从一个命令传递到另一个命令。 如果是这样,请使用管道:

    sed -n 1,1000p data/output.txt | while read -r line; do echo "$line"; done
    

    或者,为正确的工作使用正确的工具:

    head -1000 data/output.txt | while read -r ; do something; done
    

    【讨论】:

    • 这种方法的问题是 while 构造在子进程中并且不会影响其范围之外的变量,而来自 fifo 或
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    相关资源
    最近更新 更多