Each word on a separate line

前端 未结 7 1281
囚心锁ツ
囚心锁ツ 2021-01-11 09:36

I have a sentence like

This is for example

I want to write this to a file such that each word in this sentence is written to a s

相关标签:
7条回答
  • 2021-01-11 10:33

    Try using :

    string="This is for example"
    
    printf '%s\n' $string > filename.txt
    

    or taking advantage of bash word-splitting

    string="This is for example"
    
    for word in $string; do
        echo "$word"
    done > filename.txt
    
    0 讨论(0)
  • 2021-01-11 10:33

    Try use:

    str="This is for example"
    echo -e ${str// /\\n} > file.out
    

    Output

    > cat file.out 
    This
    is
    for
    example
    
    0 讨论(0)
  • 2021-01-11 10:34
    example="This is for example"
    printf "%s\n" $example
    
    0 讨论(0)
  • 2021-01-11 10:35

    A couple ways to go about it, choose your favorite!

    echo "This is for example" | tr ' ' '\n' > example.txt
    

    or simply do this to avoid using echo unnecessarily:

    tr ' ' '\n' <<< "This is for example" > example.txt
    

    The <<< notation is used with a herestring

    Or, use sed instead of tr:

    sed "s/ /\n/g" <<< "This is for example" > example.txt
    

    For still more alternatives, check others' answers =)

    0 讨论(0)
  • 2021-01-11 10:37
    $ echo "This is for example" | xargs -n1
    This
    is
    for
    example
    
    0 讨论(0)
  • 2021-01-11 10:40

    Use the fmt command

    >> echo "This is for example" | fmt -w1 > textfile.txt ; cat textfile.txt
    This
    is
    for
    example
    

    For full description of fmt and its options, check out the related man page.

    0 讨论(0)
提交回复
热议问题