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
  •  | 
  •  

Question

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

Was it helpful?

Solution

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.

OTHER TIPS

You could implement that function as

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

and use it like this

foo filename
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top