Splitting a text in Unix Splitting a text in Unix unix unix

Splitting a text in Unix


To evaluate a command and store it into a variable, use var=$(command).

All together, your code works like this:

SAMPLE_TEXT="hello.world.testing"echo "$SAMPLE_TEXT"OUT_VALUE=$(echo "$SAMPLE_TEXT" | cut -d'.' -f1)# OUT_VALUE=$(cut -d'.' -f1 <<< "$SAMPLE_TEXT") <--- alternativelyecho "output is $OUT_VALUE"

Also, note I am adding quotes all around. It is a good practice that will help you in general.


Other approaches:

$ sed -r 's/([^\.]*).*/\1/g' <<< "$SAMPLE_TEXT"hello$ awk -F. '{print $1}' <<< "$SAMPLE_TEXT"hello$ echo "${SAMPLE_TEXT%%.*}"hello


The answer by fedorqui is the correct answer. Just adding another approach...

$ SAMPLE_TEXT=hello.world.testing$ IFS=. read OUT_VALUE _ <<< "$SAMPLE_TEXT"$ echo output is $OUT_VALUE output is hello


Just to expand on @anishane's comment to his own answer:

$ SAMPLE_TEXT="hello world.this is.a test string"$ IFS=. read -ra words <<< "$SAMPLE_TEXT" $ printf "%s\n" "${words[@]}"hello worldthis isa test string$ for idx in "${!words[@]}"; do printf "%d\t%s\n" $idx "${words[idx]}"; done0   hello world1   this is2   a test string