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
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=' '
With cut
:
$ echo "Hello World Good Morning" | cut -d' ' -f2-
World Good Morning
This tells cut
to "cut" (surprisingly) based on d
elimiter 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With