下面的Perl脚本(my.pl)既可以从命令行参数中的文件读取,也可以从标准输入(STDIN)读取:

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

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

Bash中也有类似的功能吗?


当前回答

与…

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

其他回答

Use:

for line in `cat`; do
    something($line);
done

Perl的行为,OP中给出的代码可以不带参数,也可以有多个参数,如果一个参数是一个连字符-这被理解为stdin。此外,文件名总是可能带有$ARGV。 到目前为止给出的答案都没有真正模仿Perl在这些方面的行为。这里有一个纯Bash的可能性。诀窍在于适当地使用exec。

#!/bin/bash

(($#)) || set -- -
while (($#)); do
   { [[ $1 = - ]] || exec < "$1"; } &&
   while read -r; do
      printf '%s\n' "$REPLY"
   done
   shift
done

文件名可在$1。

如果没有给出参数,则人为地将-设置为第一个位置参数。然后循环参数。如果参数不是-,则使用exec重定向filename中的标准输入。如果重定向成功,则使用while循环进行循环。我使用标准的REPLY变量,在这种情况下,您不需要重置IFS。如果你想要另一个名字,你必须像这样重置IFS(当然,除非你不想这样做,并且知道你在做什么):

while IFS= read -r line; do
    printf '%s\n' "$line"
done

我认为这是最直接的方法:

$ cat reader.sh
#!/bin/bash
while read line; do
  echo "reading: ${line}"
done < /dev/stdin

--

$ cat writer.sh
#!/bin/bash
for i in {0..5}; do
  echo "line ${i}"
done

--

$ ./writer.sh | ./reader.sh
reading: line 0
reading: line 1
reading: line 2
reading: line 3
reading: line 4
reading: line 5

更准确的说……

while IFS= read -r line ; do
    printf "%s\n" "$line"
done < file

每当IFS中断输入流时,回显解决方案就添加新行。@fgm的回答可以稍微修改一下:

cat "${1:-/dev/stdin}" > "${2:-/dev/stdout}"