下面的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中也有类似的功能吗?
当前回答
我将上述所有答案结合起来,创建了一个适合我需要的shell函数。这是我的两台Windows 10机器的Cygwin终端,我在它们之间有一个共享文件夹。我需要能够处理以下问题:
Cat文件。cpp | tx Tx < file.cpp tx file.cpp
如果指定了特定的文件名,则在复制过程中需要使用相同的文件名。在输入数据流通过管道的地方,我需要生成一个包含小时、分钟和秒的临时文件名。共享的主文件夹包含以星期为单位的子文件夹。这是为了组织的目的。
看,我需要的终极剧本
tx ()
{
if [ $# -eq 0 ]; then
local TMP=/tmp/tx.$(date +'%H%M%S')
while IFS= read -r line; do
echo "$line"
done < /dev/stdin > $TMP
cp $TMP //$OTHER/stargate/$(date +'%a')/
rm -f $TMP
else
[ -r $1 ] && cp $1 //$OTHER/stargate/$(date +'%a')/ || echo "cannot read file"
fi
}
如果有任何方法,你可以看到进一步优化这一点,我想知道。
其他回答
请尝试以下代码:
while IFS= read -r line; do
echo "$line"
done < file
也许最简单的解决方案是使用合并重定向操作符重定向标准输入:
#!/bin/bash
less <&0
标准输入是文件描述符0。上面的代码将通过管道传输到bash脚本的输入发送到less的标准输入中。
阅读有关文件描述符重定向的更多信息。
这是最简单的方法:
#!/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
Use:
for line in `cat`; do
something($line);
done
作为一种变通方法,你可以使用/dev目录下的stdin设备:
....| for item in `cat /dev/stdin` ; do echo $item ;done