bash命令在while循环中重定向stdin(使用sed)

时间:2017-06-22 10:54:29

标签: bash while-loop stdin readfile

我正在尝试仅从文件(output.txt)到while循环的stdin从1到1000。

我尝试过这样的事情:

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

3 个答案:

答案 0 :(得分:4)

刚试过:

public class Server {

public static void main(String[] args) throws Exception {

    ServerSocket sock = new ServerSocket(5151);
    System.out.println("Server is running!");

    Socket client = sock.accept();
    System.out.println("Client connected from " + client.getLocalAddress());

    InputStream istream = client.getInputStream();
    DataInputStream dis = new DataInputStream(istream);

    String msg = dis.readLine();

    System.out.println(msg);

    OutputStream ostream = client.getOutputStream();
    BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(ostream));

    String msgBack = "Thank you for connecting!";
    bw1.write(msgBack);

    bw1.close();
    dis.close();
    istream.close();
    client.close();
    sock.close();

}

添加另一个角括号&#34;&lt;&#34;诀窍......如果有人可以解释那可能很有趣。

由于

答案 1 :(得分:2)

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

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

mkfifo myfifo

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

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

答案 2 :(得分:1)

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

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