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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

How to echo a list on seperate lines in unix

  • 03-08-2011 3:24pm
    #1
    Registered Users, Registered Users 2 Posts: 5,708 ✭✭✭


    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, Registered Users 2 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, Registered Users 2 Posts: 3,141 ✭✭✭ocallagh


    edit: misread OP


  • Registered Users, Registered Users 2 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, Registered Users 2 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