Results 1 to 5 of 5

Thread: Pipe into a for loop

  1. #1
    Join Date
    Sep 2007
    Beans
    229

    Pipe into a for loop

    I want to send the output of some command into a for loop in bash. How can I do that?

    Here is an example: let's say I want to run cat, and then send the output of it to a for loop, which reads each line, and tells you the character length of that line. It should be sometihng like:

    cat FILE | for i in $1; do print length($i); done

    But that doesn't really work. So how can I do that? (I don't want to write and save a script file, I want to do it all on the fly using pipes only).

  2. #2
    Join Date
    Apr 2012
    Beans
    5,341

    Re: Pipe into a for loop

    You can do that kind of thing with read and while e.g.

    Code:
    while read line; do something with "$line"; done < file
    No cats harmed in the making of this script (uses a < input redirection instead of piping from cat)

  3. #3
    Join Date
    Aug 2011
    Location
    52° N 6° E
    Beans
    2,272
    Distro
    Xubuntu 14.04 Trusty Tahr

    Re: Pipe into a for loop

    To show you a command I used to generate a list of words in a collection of tex files, sorted by word length:
    Code:
    cat file1.tex file2.tex file3.tex | \
    sed -f filterglscommands.sed | sed -f filterother.sed | \
    tr -s ' ' '\n' | tr '[:upper:]' '[:lower:]' | sort | uniq | \
    while read w; do echo ${#w} $w; done | \
    sort -n >wordlength.txt
    Similar to what you're doing, you can take the red lines. ${#w} returns the length of string w. The sed scripts are used to do some limited macro expansion and remove all other commands and interpunction.

  4. #4
    Join Date
    Feb 2007
    Location
    Romania
    Beans
    Hidden!
    Distro
    Ubuntu Development Release

    Re: Pipe into a for loop

    hojjat, please check out BashFAQ 001 (link in my signature).

  5. #5
    Join Date
    Sep 2007
    Beans
    229

    Re: Pipe into a for loop

    All were very good answers. This one was my favorite

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
  •