Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a line into words in bash

Tags:

bash

I would like to split a line into words. I know this can be done with this

For word in $line; do echo $word; done  

But I want to make group of 3-3 words. So my question is, how can I split a line in group of 3-3 words ?

For example

Input : I am writing this line for testing the code.  

Output :  
I am writing
this line for
testing the code.  
like image 278
vikas ramnani Avatar asked Jun 26 '12 12:06

vikas ramnani


People also ask

How do I split a string into words in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How do you separate text in Linux?

To split a file into pieces, you simply use the split command. By default, the split command uses a very simple naming scheme. The file chunks will be named xaa, xab, xac, etc., and, presumably, if you break up a file that is sufficiently large, you might even get chunks named xza and xzz.


1 Answers

Read the words three at a time. Set the line being read from to the remainder:

while read -r remainder
do
    while [[ -n $remainder ]]
    do
        read -r a b c remainder <<< "$remainder"
        echo "$a $b $c"
    done
done < inputfile
like image 198
Dennis Williamson Avatar answered Nov 15 '22 05:11

Dennis Williamson