パイプを介してファイルを読み取る

パイプを介してファイルを読み取る

私はファイルの内容を読み、行末形式を維持するためにインターネットハックを使用するサンプルコードを書いています。シェルファイルを「pipeTesting」、テキストファイルを「textExample」と呼びます。このファイルをシェルスクリプトの引数として呼び出すと、「pipeTesting」が機能します。

ただし、場合によっては、パイプラインを介してファイルが検索されます。コマンドを使用してパイプラインテストにテキストを提供すると、何も印刷されないため、catパラメータはまったくありませんecho $@。 1つの注意点は、-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--}"

またはStefanが指摘したように、

cat -- "$@"

コマンドラインで複数のファイル名を指定することもできます。


短く:

alias PipeTester=cat

実際に実行中の作業は再実装に近いですcatPipeTester実際、スクリプトは、catエイリアスを介して実行する上記のスクリプトに置き換えることができます。

おすすめ記事