Reading in own function from a pipe line by line and approaching the whole file as one entity at the same time

StackOverflow https://stackoverflow.com/questions/22658948

  •  21-06-2023
  •  | 
  •  

문제

Is it possible to read from a pipe line by line and have access to the whole file as one entity, let's say for grep, at the same time?

function()
{ 
while read data 
do
# processing line by line, using $data 
grep "string" WHOLE_FILE | ...
# processing 
done
}

cat some_file | function | ...

Thank you

도움이 되었습니까?

해결책

Not implicitly, but

{ echo some_file; cat some_file; } | function | ...

with

function () {
    read filename
    while read data; do
        grep "string" $filename | ...
    done
}

should do what you want.

If standard input is connected directly to a file, you might be able to use readlink on a file such as /proc/self/fd/0 (in Linux) to get the name of the file opened on standard input. However, standard input may come from a pipe, which may come from an arbitrary program writing directly to the pipe, rather than an actual file.

다른 팁

You could implement that function as

foo() {
    while read data; do
        grep "$data" $1
    done < $1
}

and use it like this

foo filename
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top