Results 1 to 4 of 4

Thread: Strange output: Read a TXT-File in a with a for-loop

  1. #1

    Default Strange output: Read a TXT-File in a with a for-loop

    Hello all,

    I have a problem, which I don't understand:

    Here is my textfile "test.txt" with the following content:
    Code:
    hello_world 123
    byebye_world 456
    I wrote a script, to readout every line with a for-loop:
    Code:
    #!/bin/bash
    for F in `<test.txt`; do
            echo "$F"
    done
    The output of the script is like this:
    Code:
    root@host1:/tmp> ./test.sh
    hello_world
    123
    byebye_world
    456
    And here is my question: Why are the numbers on a separate line? I tried to delete newlines / carriage returns with the "tr"-command -> no success.

    How can I read the textfile with a for-loop having the numbers on the same line as the text?

    Any hints?

    Thanks a lot.
    Tom

  2. #2
    Join Date
    Jun 2008
    Location
    UTC+10
    Posts
    9,686
    Blog Entries
    4

    Default Re: Strange output: Read a TXT-File in a with a for-loop

    It's important to understand what the backtick operator actually does. It runs the command and then presents the entire output as a string to be used. So `<test.txt` returns this string:

    Code:
    hello_world 123\nbyebye_world 456\n
    where \n is a newline. Next the for statement takes each of the words in the string and sets the loop variable to it. So the words are:

    Code:
    hello_world
    123
    byebye_world
    456
    since newline is a word separator. So nothing about reading lines in there.

    What you really want is something like this:

    Code:
    while read F
    do
      echo $F
    done < test.txt
    But check the output, because there are some subtleties for the read. For one thing, leading whitespace is discarded. There are options to the read directive you can use to modify behaviour.

  3. #3

    Thumbs up Re: Strange output: Read a TXT-File in a with a for-loop

    Thanks a lot for your explanation.

  4. #4

    Default Re: Strange output: Read a TXT-File in a with a for-loop

    to process files, you can use awk.

Posting Permissions

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