通过管道读取文件

通过管道读取文件

我编写了一个示例代码,用于使用互联网上的 hack 来读取文件的内容并维护行尾格式。我将 shell 文件称为“pipeTesting”,将文本文件称为“textExample”。如果我将该文件作为 shell 脚本的参数调用,“pipeTesting”就会起作用。

然而,在某些情况下,文件是通过管道检索的;如果我使用命令向 pipelineTesting 提供文本cat,则根本没有参数,因为echo $@不打印任何内容。需要注意的是,我必须-p /dev/stdin创建一个用于管道使用的案例和一个用于参数使用的案例。

有没有办法在管道的情况下显示文件的内容并保持行尾?

谢谢。

代码看起来像这样:

#!/bin/bash

if [ -p /dev/stdin ]; then
    echo $@
else
    while read
    do
        echo $REPLY
    done < $1
fi
exit 0

其应用是:

$ cat textExample.txt
Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning- little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door-
Bird or beast upon the sculptured bust above his chamber door,
With such name as "Nevermore."
$ pipeTester textExample.txt 
Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning- little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door-
Bird or beast upon the sculptured bust above his chamber door,
With such name as "Nevermore."
$ cat textExample.txt | pipeTester 
_

答案1

#!/bin/sh

infile=${1--}

cat "$infile"

也就是说,将infile变量设置为第一个参数的名称,但如果该名称不可用,请将其设置为-. cat作为-输入文件名将从标准输入(即从管道或重定向)读取。


较短:

#!/bin/sh

cat -- "${1--}"

或者,正如斯特凡指出的那样,

cat -- "$@"

这还允许您在命令行上给出多个文件名。


还更短:

alias PipeTester=cat

您所做的或多或少是重新实现cat.PipeTester事实上,您的脚本可能会被替换cat,上面的脚本是通过别名来实现的。

相关内容