0

I have setup like this:

    #read a list of files
    tr -d \\015 < sample.txt | while IFS=, read -r NAME
        do
            #grep for lines and do stuff
            for VAR in $(grep '.*: {$' $NAME)
                do
                do some stuff
                done
        done

Problem is this. It doesn't work, because the for VAR in $(grep '.*: {$' $NAME) adds an unnecessary space and newline to its results.

If I echo $VAR I get the following:

    blahblahblah: 
    {

Now consider this code:

    #read a list of files
    tr -d \\015 < sample.txt | while IFS=, read -r NAME
        do
            VAR=$(grep '.*: {$' $NAME)
            echo $VAR
        done

If I echo $VAR here I get:

    blahblahblah: {

Why do I get the extra newline in the first example?

Sidereal
  • 111
  • 3
  • 5
    `for VAR in ...` iterates over *words*, not lines, so "blahblahblah:" and "{" are treated as separate items. You can change the definition of "word" to be more like a line, but really you should use another `while read` loop. See [BashFAQ #1](https://mywiki.wooledge.org/BashFAQ/001). Also, you should almost always double-quote variable references (to avoid weird parsing), and use lower- or mixed-case variable names (to avoid conflicts with the all-caps names with special meanings). – Gordon Davisson Jun 14 '19 at 03:17
  • ....see https://mywiki.wooledge.org/Quotes and https://stackoverflow.com/q/673055/1745001 – Ed Morton Jun 14 '19 at 11:31

0 Answers0