Results 1 to 2 of 2

Thread: Using Tee and Grep together to get output but also send output to a file

  1. #1
    Join Date
    Jan 2019
    Beans
    1

    Using Tee and Grep together to get output but also send output to a file

    Hello everybody,

    I recently ran into the following problem:

    I want to put my output of a command into a file like this:

    Code:
    ls >> example.txt
    but at the same time i want to see the output of it.

    Now if I would type

    HTML Code:
    ls
    i would get as output:

    Code:
    file1
    file2
    file3
    Now i want to grep only file1 and redirect the output "file1" into my example.txt while still being able to see all 3 files as output of my ls in my normal shell.

    I got to the conclusion that i can use tee but i won't see the full output if I only use it with grep.

    Desired result:

    Input:
    Code:
    This is what I want
    output in shell:
    Code:
    file1
    file2
    file3
    example.txt
    Code:
    file1

  2. #2
    Join Date
    Aug 2011
    Location
    52.5° N 6.4° E
    Beans
    6,806
    Distro
    Xubuntu 22.04 Jammy Jellyfish

    Re: Using Tee and Grep together to get output but also send output to a file

    Use process substitution:
    Code:
    ls | tee >(grep example >> example.txt)
    The >(...) syntax creates a named pipe. tee will write to this pipe and to the terminal, the shell connects standard input of whatever is in the parentheses to the reading end of the pipe.

    Edit: An interesting example I occasionally run:
    Code:
    cat file1.tex file2.tex file3.tex | sed -f glsstuff.sed.00 | sed -f glsstuff.sed.01 | sed -f filter.sed | \
    tr -s ' ' '\n' | tr '[:upper:]' '[:lower:]' | sed /^$/d | sort | tee >(uniq -c | sort -no wordfreq.txt) | uniq | \
    tee wordlist.txt | while read w; do echo ${#w} $w; done | sort -no wordlength.txt
    This reads a bunch of .tex files, runs them through some filters and uses tee to generate three word lists: all words by frequency, alphabetically and by length. Note the process substitution on the second line.
    Last edited by Impavidus; January 30th, 2019 at 07:13 PM.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •