如何在 Bash 中读取文件或标准输入 [英] How to read from a file or standard input in Bash

查看:48
本文介绍了如何在 Bash 中读取文件或标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 Perl 脚本 (my.pl) 可以从命令行参数中的文件或 标准输入 (STDIN):

The following Perl script (my.pl) can read from either the file in the command line arguments or from standard input (STDIN):

while (<>) {
   print($_);
}

perl my.pl 将从标准输入中读取,而 perl my.pl a.txt 将从 a.txt 中读取.这很方便.

perl my.pl will read from standard input, while perl my.pl a.txt will read from a.txt. This is very handy.

Bash 中是否有等价物?

Is there an equivalent in Bash?

推荐答案

如果使用文件名作为第一个参数 $1 调用脚本,则以下解决方案从文件中读取,否则从标准输入中读取.

The following solution reads from a file if the script is called with a file name as the first parameter $1 and otherwise from standard input.

while read line
do
  echo "$line"
done < "${1:-/dev/stdin}"

替换 ${1:-...} 如果已定义,则采用 $1.否则使用自己进程的标准输入的文件名.

The substitution ${1:-...} takes $1 if defined. Otherwise, the file name of the standard input of the own process is used.

这篇关于如何在 Bash 中读取文件或标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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