Search code examples
awkhp-ux

evaluate awk and keep lines


I have txt file with data inside like:

string1,string2,string3,string4,string5

I want to assign awk for string3 to a variable dc like:

dc=$(awk -F',' '{print $3}' file)

But then when I evaluate dc with $dc to see output per line, not space separated.

Now with: echo $dc, I see:

string3 string3 string3 string3 string3 string3 string3

I want to see:

string3
string3
string3
string3

Solution

  • Nothing to do with awk, you just need quotes around $dc:

    $ cat x
    a
    b
    c
    
    $ dc=$(cat x)
    
    $ echo $dc
    a b c
    
    $ echo "$dc"
    a
    b
    c
    

    The way I understand it is, without the quotes, you're giving echo a list of arguments separated by whitespace (in other words, none of those arguments include a newline). With the quotes, you're giving echo a single argument, which is a string that itself includes the newlines.