下面的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中也有类似的功能吗?
当前回答
#!/usr/bin/bash
if [ -p /dev/stdin ]; then
#for FILE in "$@" /dev/stdin
for FILE in /dev/stdin
do
while IFS= read -r LINE
do
echo "$@" "$LINE" #print line argument and stdin
done < "$FILE"
done
else
printf "[ -p /dev/stdin ] is false\n"
#dosomething
fi
运行:
echo var var2 | bash std.sh
结果:
var var2
运行:
bash std.sh < <(cat /etc/passwd)
结果:
root:x:0:0::/root:/usr/bin/bash
bin:x:1:1::/:/usr/bin/nologin
daemon:x:2:2::/:/usr/bin/nologin
mail:x:8:12::/var/spool/mail:/usr/bin/nologin
其他回答
下面的解决方案从文件读取(如果脚本调用时将文件名作为第一个参数$1),否则从标准输入读取。
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
替换${1:-…}如果定义了,则接受$1。否则,使用自己进程的标准输入的文件名。
这个很容易在终端上使用:
$ echo '1\n2\n3\n' | while read -r; do echo $REPLY; done
1
2
3
#!/usr/bin/bash
if [ -p /dev/stdin ]; then
#for FILE in "$@" /dev/stdin
for FILE in /dev/stdin
do
while IFS= read -r LINE
do
echo "$@" "$LINE" #print line argument and stdin
done < "$FILE"
done
else
printf "[ -p /dev/stdin ] is false\n"
#dosomething
fi
运行:
echo var var2 | bash std.sh
结果:
var var2
运行:
bash std.sh < <(cat /etc/passwd)
结果:
root:x:0:0::/root:/usr/bin/bash
bin:x:1:1::/:/usr/bin/nologin
daemon:x:2:2::/:/usr/bin/nologin
mail:x:8:12::/var/spool/mail:/usr/bin/nologin
与…
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
这是最简单的方法:
#!/bin/sh
cat -
用法:
$ echo test | sh my_script.sh
test
要将stdin分配给变量,您可以使用:stdin =$(cat -)或只是简单的stdin =$(cat)作为操作符是不必要的(根据@mklement0注释)。
要解析标准输入中的每一行,请尝试以下脚本:
#!/bin/bash
while IFS= read -r line; do
printf '%s\n' "$line"
done
要从文件或stdin中读取(如果参数不存在),您可以将其扩展为:
#!/bin/bash
file=${1--} # POSIX-compliant; ${1:--} can be used either.
while IFS= read -r line; do
printf '%s\n' "$line" # Or: env POSIXLY_CORRECT=1 echo "$line"
done < <(cat -- "$file")
Notes: - read -r - Do not treat a backslash character in any special way. Consider each backslash to be part of the input line. - Without setting IFS, by default the sequences of Space and Tab at the beginning and end of the lines are ignored (trimmed). - Use printf instead of echo to avoid printing empty lines when the line consists of a single -e, -n or -E. However there is a workaround by using env POSIXLY_CORRECT=1 echo "$line" which executes your external GNU echo which supports it. See: How do I echo "-e"?
参见:当没有参数传递时如何读取stdin ?在stackoverflow SE