Siddharth
Siddharth

Reputation: 9574

Weird bash results using cut

I am trying to run this command:

./smstocurl SLASH2.911325850268888.911325850268896

smstocurl script:

#SLASH2.911325850268888.911325850268896
model=$(echo \&model=$1 | cut -d'.' -f 1)
echo $model
imea1=$(echo \&simImea1=$1 | cut -d'.' -f 2)
echo $imea1
imea2=$(echo \&simImea2=$1 | cut -d'.' -f 3)
echo $imea2
echo $model$imea1$imea2

Result Received

&model=SLASH2911325850268888911325850268896

Result Expected

&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

What am I missing here ?

Upvotes: 0

Views: 89

Answers (3)

user3442743
user3442743

Reputation:

awk way

awk -F. '{print "&model="$1"&simImea1="$2"&simImea2="$3}' <<< "SLASH2.911325850268888.911325850268896"

or

awk -F. '$0="&model="$1"&simImea1="$2"&simImea2="$3' <<< "SLASH2.911325850268888.911325850268896"

output

&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

Upvotes: 1

fedorqui
fedorqui

Reputation: 289735

You are cutting based on the dot .. In the first case your desired string contains the first string, the one containing &model, so then it is printed.

However, in the other cases you get the 2nd and 3rd blocks (-f2, -f3), so that the imea text gets cutted off.

Instead, I would use something like this:

while IFS="." read -r model imea1 imea2
do
    printf "&model=%s&simImea1=%s&simImea2=%s\n" $model $imea1 $imea2
done <<< "$1"

Note the usage of printf and variables to have more control about what we are writing. Using a lot of escapes like in your echos can be risky.

Test

while IFS="." read -r model imea1 imea2; do printf "&model=%s&simImea1=%s&simImea2=%s\n" $model $imea1 $imea2
done <<< "SLASH2.911325850268888.911325850268896"

Returns:

&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

Alternatively, this sed makes it:

sed -r 's/^([^.]*)\.([^.]*)\.([^.]*)$/\&model=\1\&simImea1=\2\&simImea2=\3/' <<< "$1"

by catching each block of words separated by dots and printing back.

Upvotes: 4

Kalanidhi
Kalanidhi

Reputation: 5092

You can also use this way

Run:

./program SLASH2.911325850268888.911325850268896

Script:

#!/bin/bash
String=`echo $1 | sed "s/\./\&simImea1=/"`
String=`echo $String | sed "s/\./\&simImea2=/"`
echo "&model=$String

Output:

&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

Upvotes: 1

Related Questions