Find the answer to your Linux question:
Results 1 to 5 of 5
hey all, ./test Code: #!/bin/bash for line in $(cat data1) do echo $line done data1 Code: ello there nobody says a word Output after running the file : Code: hello ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Aug 2012
    Posts
    7

    Getting Same Lines from File(BASH)


    hey all,

    ./test
    Code:
    #!/bin/bash
    for line in $(cat data1)
    do
    echo $line
    done
    data1
    Code:
    ello there
    nobody says a word
    Output after running the file :
    Code:
    hello
    there
    nobody
    says
    a
    word
    While output should be this :
    Code:
    hello there
    nobody says a word
    Could anyone explain/fix this?

    I could use other kinds of loops that would do the job! but I am interested in understanding this kind of loop.

    thanks a lot.

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Quote Originally Posted by eawedat View Post
    Could anyone explain/fix this?

    I could use other kinds of loops that would do the job! but I am interested in understanding this kind of loop.
    Try using double-quotes to preserve the spaces within the $line variable, e.g.:
    Code:
    #!/bin/bash
    for line in "$(cat data1)"
    do
    echo "$line"
    done

  3. #3
    Just Joined!
    Join Date
    Aug 2012
    Posts
    7
    thank you

  4. $spacer_open
    $spacer_close
  5. #4
    Linux Newbie
    Join Date
    Jun 2012
    Location
    SF Bay area
    Posts
    217
    Well using double quotes around "$(cat file)" might appear to do what you want, but it's not looping anymore.

    The ENTIRE file is assigned to "line", including LF's, so it just does one echo and ends.

    Try this variation to see what I mean...

    Code:
    #!/bin/bash
    off=1
    for line in $(cat data1)
    do
       echo "${off}. ${line}"
       off=$(( off + 1 ))
    done
    Then put the double quote around the "$(cat file)" bit and you'll see it only goes through the loop once. I think they key to understanding how this work is that a "for VAR in LIST" shell statement does break on LF's. You get words not lines and a blank and a LF both count as separating words.
    Last edited by cnamejj; 09-06-2012 at 09:49 AM. Reason: broken 'code' tags

  6. #5
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    good call, cnamejj - no loopy.

    this method would have been my instinct, but i was trying to preserve the OP's loop:

    Code:
    #!/bin/bash
    declare -i n=1
    while read line1; do
      echo "line $n: '$line1'"
      let n+=1
    done < <(cat data1)

Posting Permissions

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