Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

How to echo a list on seperate lines in unix

Options
  • 03-08-2011 4:24pm
    #1
    Registered Users Posts: 5,560 ✭✭✭


    Hi - i have a variable (lets just call it $list) and want to output it line by line to a file. Does echo provide such a facility directly or do we need a for loop


Comments

  • Registered Users Posts: 255 ✭✭boblong


    I'm sure there is some awesome way using just echo and I hope someone else posts their insight.

    Presuming $list is an array, here's what I would do:
    #!/bin/bash
    
    arr=(hello world something etc)
    echo ${arr[@]} | tr ' ' '\n' > file.txt
    

    This is probably quite the hack, but there it is :)


  • Registered Users Posts: 3,140 ✭✭✭ocallagh


    edit: misread OP


  • Registered Users Posts: 1,311 ✭✭✭Procasinator


    boblong wrote: »
    I'm sure there is some awesome way using just echo and I hope someone else posts their insight.

    Presuming $list is an array, here's what I would do:
    #!/bin/bash
    
    arr=(hello world something etc)
    echo ${arr[@]} | tr ' ' '\n' > file.txt
    

    This is probably quite the hack, but there it is :)

    Won't work for strings with spaces in them, like:
    arr=('hello world' 'something' 'etc')
    

    As hello world would be split.

    One solution would be to replace all the spaces in the strings with a character you know won't be in the input (in this example, _), and tr them back to spaces.
    echo ${arr[@]// /_} | tr '_ ' ' \n'
    

    However OP, I believe your best best is to use a for loop on ${list[@]}.


  • Registered Users Posts: 368 ✭✭backboiler


    Hi - i have a variable (lets just call it $list) and want to output it line by line to a file. Does echo provide such a facility directly or do we need a for loop

    Does the input arrive line-by-line?
    Have you seen the difference between
    echo $line
    
    and
    echo "$line"
    
    (i.e. with double quotes). The latter may do what you want if the input is formatted that way since it stops the shell interpreting whitespace sequences (it converts them to a single space).


Advertisement