Unix text separation

I am writing a simple script that breaks a variable that contains some text using the code below:

#!/bin/sh

SAMPLE_TEXT=hello.world.testing

echo $SAMPLE_TEXT
OUT_VALUE=$SAMPLE_TEXT | cut -d'.' -f1

echo output is $OUT_VALUE

I expect output like output is hello, but when I run this program, I get output like output is. Please let me know where I am going wrong?

+3
source share
3 answers

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

All together, your code works as follows:

SAMPLE_TEXT="hello.world.testing"

echo "$SAMPLE_TEXT"
OUT_VALUE=$(echo "$SAMPLE_TEXT" | cut -d'.' -f1)
# OUT_VALUE=$(cut -d'.' -f1 <<< "$SAMPLE_TEXT") <--- alternatively

echo "output is $OUT_VALUE"

Also, note that I am adding quotes around. This is a good practice that will help you overall.


Other approaches:

$ sed -r 's/([^\.]*).*/\1/g' <<< "$SAMPLE_TEXT"
hello

$ awk -F. '{print $1}' <<< "$SAMPLE_TEXT"
hello

$ echo "${SAMPLE_TEXT%%.*}"
hello
+4
source

Fedorqui's answer 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
+4
source

, @anishane :

$ SAMPLE_TEXT="hello world.this is.a test string"
$ IFS=. read -ra words <<< "$SAMPLE_TEXT" 

$ printf "%s\n" "${words[@]}"
hello world
this is
a test string

$ for idx in "${!words[@]}"; do printf "%d\t%s\n" $idx "${words[idx]}"; done
0   hello world
1   this is
2   a test string
+2

All Articles