Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a sentence using space in bash script

Tags:

bash

shell

ubuntu

How can I split a sentence using space, and print from second word onwards?

For example, if my sentence is Hello World Good Morning, then I want to print like:

World
Good
Morning
like image 351
Uvais Ibrahim Avatar asked Nov 29 '22 11:11

Uvais Ibrahim


2 Answers

You can change the record separator to a space in awk and print from the second record onwards:

$ awk 'NR>1' RS=' ' <<<"Hello World Good Morning"
World
Good
Morning

As pointed out in the comments, there is also an extra blank line at the end of the output. This comes from the newline at the end of the input. If you are using GNU awk, it can be suppressed by setting the record separator to the [[:space:]] character class:

$ awk 'NR>1' RS='[[:space:]]' <<<"Hello World Good Morning"

Alternatively, as suggested by fedorqui, you can use printf instead of echo to pass the variable to awk:

printf '%s' 'Hello World Good Morning' | awk 'NR>1' RS=' '
like image 21
Tom Fenech Avatar answered Dec 02 '22 00:12

Tom Fenech


With cut:

$ echo "Hello World Good Morning" | cut -d' ' -f2-
World Good Morning

This tells cut to "cut" (surprisingly) based on delimiter space and print from 2nd field up to the end.


With sed:

$ echo "Hello World Good Morning" | sed 's/^[^ ]* //'
World Good Morning

This gets, from the beginning of the line (^), a block of characters not containing a space ([^ ]*) and then a space and replaces it with empty content. This way, the first word is deleted.


With pure bash:

$ while IFS=" " read -r _ b; do echo "$b"; done <<< "Hello World Good Morning"
World Good Morning

This sets the field separator to the space and reads the first block in a dummy variable _ and the rest in the variable $b. Then, it prints $b.


Also in awk, using this Ed Morton's approach:

$ echo 'Hello World Good Morning' | awk '{sub(/([^ ]+ +){1}/,"")}1'
World Good Morning

This replaces 1 block of not space characters + block of spaces with an empty string.

like image 120
fedorqui 'SO stop harming' Avatar answered Dec 02 '22 00:12

fedorqui 'SO stop harming'