Splitting a string into words in bash

I would like to split the string into words. I know that this can be done with this

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

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

for instance

 Input : I am writing this line for testing the code. Output : I am writing this line for testing the code. 
+4
source share
7 answers

In the beginning you can use this, which reads each word into an array

 #!/bin/bash total=0 while read do for word in $REPLY do A[$total]=$word total=$(($total+1)) done done < input.txt for i in "${A[@]}" do echo $i done 

The next step is to use seq or similarly to loop through an array and print it in groups of three.

0
source

How about the paste command

 for word in $line; do echo $word; done | paste - - - for word in $line; do echo $word; done | paste -d" " - - - 
+3
source

Read the words three at a time. Set the line read from the rest of:

 while read -r remainder do while [[ -n $remainder ]] do read -rabc remainder <<< "$remainder" echo "$a $b $c" done done < inputfile 
+3
source

Easy exercise of regular expression.

 sed -e "s/\([^\ ]*\ [^\ ]*\ [^\ ]*\)\ /\1\\`echo -e '\n\r'`/g" 

The only tricky part is getting a new line in sed, since there is no standard for this.

 $ echo "I am writing this line for testing the code."|sed -e "s/\([^\ ]*\ [^\ ]*\ [^\ ]*\)\ /\1\\`echo -e '\n\r'`/g" I am writing this line for testing the code. 

Welcome.

+1
source

Just use set to indicate your input as positional arguments and process them in groups of three. This way you don't need anything fantastic or bash-specific:

 line="I am writing this line for testing the code." set junk $line shift while [ $# -ge 3 ]; do echo "Three words: $1 $2 $3" shift 3 done 
+1
source

There is a non-trivial direct solution:

 #!/bin/bash path_to_file=$1 while read line do counter=1; for word in $line do echo -n $word" "; if (($counter % 3 == 0)) then echo ""; fi let counter=counter+1; done done < ${path_to_file} 

Save this in a script, give it a name (for example, test.sh) and set it to run mode. Then, if your text is saved in "myfile.txt", call it like this:

 test.sh myfile.txt 
0
source

Here is an example of a possible solution.

 #!/bin/bash line="I am writing this line for testing the code." i=0 for word in $line; do ((++i)) if [[ $i -eq 3 ]]; then i=0 echo "$word" else echo -ne "$word " fi done 
0
source

All Articles