下面的Perl脚本(my.pl)既可以从命令行参数中的文件读取,也可以从标准输入(STDIN)读取:
while (<>) {
print($_);
}
Perl my.pl将从标准输入中读取,而Perl my.pl .txt将从a.txt中读取。这很方便。
Bash中也有类似的功能吗?
下面的Perl脚本(my.pl)既可以从命令行参数中的文件读取,也可以从标准输入(STDIN)读取:
while (<>) {
print($_);
}
Perl my.pl将从标准输入中读取,而Perl my.pl .txt将从a.txt中读取。这很方便。
Bash中也有类似的功能吗?
当前回答
下面的解决方案从文件读取(如果脚本调用时将文件名作为第一个参数$1),否则从标准输入读取。
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
替换${1:-…}如果定义了,则接受$1。否则,使用自己进程的标准输入的文件名。
其他回答
Use:
for line in `cat`; do
something($line);
done
与…
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
我得到以下输出:
忽略标准输入中的1265个字符。使用“-stdin”或“-”来说明如何处理管道输入。
然后决定用for:
Lnl=$(cat file.txt | wc -l)
echo "Last line: $Lnl"
nl=1
for num in `seq $nl +1 $Lnl`;
do
echo "Number line: $nl"
line=$(cat file.txt | head -n $nl | tail -n 1)
echo "Read line: $line"
nl=$[$nl+1]
done
每当IFS中断输入流时,回显解决方案就添加新行。@fgm的回答可以稍微修改一下:
cat "${1:-/dev/stdin}" > "${2:-/dev/stdout}"
以下是使用标准sh(在Debian上用Dash测试)的工作,相当可读,但这是一个品味问题:
if [ -n "$1" ]; then
cat "$1"
else
cat
fi | commands_and_transformations
详细信息:如果第一个参数非空,则cat该文件,否则cat标准输入。然后整个if语句的输出由command_and_transforms处理。
更准确的说……
while IFS= read -r line ; do
printf "%s\n" "$line"
done < file