使用Bash一次读取n行 [英] Read n lines at a time using Bash

查看:87
本文介绍了使用Bash一次读取n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了help read页,但是仍然没有任何意义.不知道要使用哪个选项.

I read the help read page, but still don't quite make sense. Don't know which option to use.

如何使用Bash一次读取N行?

How can I read N lines at a time using Bash?

推荐答案

这比看起来要难.问题是如何保持文件句柄.

This is harder than it looks. The problem is how to keep the file handle.

解决方案是创建另一个新的文件句柄,其作用类似于stdin(文件句柄0),但是是独立的,然后根据需要从中读取.

The solution is to create another, new file handle which works like stdin (file handle 0) but is independent and then read from that as you need.

#!/bin/bash

# Create dummy input
for i in $(seq 1 10) ; do echo $i >> input-file.txt ; done

# Create new file handle 5
exec 5< input-file.txt

# Now you can use "<&5" to read from this file
while read line1 <&5 ; do
        read line2 <&5
        read line3 <&5
        read line4 <&5

        echo "Four lines: $line1 $line2 $line3 $line4"
done

# Close file handle 5
exec 5<&-

这篇关于使用Bash一次读取n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆