Search code examples
bashunixcut

Splitting a text in Unix


I am writing a simple script that splits a variable that holds some text by using below code:

#!/bin/sh

SAMPLE_TEXT=hello.world.testing

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

echo output is $OUT_VALUE

I am expecting output as output is hello but when I run this program then I am getting output as output is. Please let me know where I am doing mistake?


Solution

  • 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") <--- alternatively
    
    echo "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