Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut an existing variable and assign to a new variable in bash

Tags:

linux

bash

!/bin/bash
VAR=$(some curl commands)
token =$(cut -c 18-53 $VAR)
echo $token

I want to use VAR variable in my cut command but, when I use like this it says;

No such file or directory

I just wanna cut VAR(output of curl command) from 18.char to 53.char. Any suggestion ?

like image 625
Berkay Kirmizioglu Avatar asked Oct 28 '25 12:10

Berkay Kirmizioglu


1 Answers

Let's define an example var:

$ var='The quick brown fox jumped over the lazy dog on the way to the market'

Now let's select characters 18 through 53 using cut:

$ echo $(cut -c 18-53 <<<"$var")
ox jumped over the lazy dog on the w

Because cut expects to read from standard input (if not a file), we use <<< to tell bash to provide the contents of $var on standard input. This is called a here string.

Alternatively, we can select the same characters using bash alone:

$ echo ${var:17:36}
ox jumped over the lazy dog on the w

The construct ${var:17:36} is called substring expansion. It selects 36 characters starting from position 17. (In bash, unlike cut, the first character is numbered zero.)

We can, of course, assign the selected string to a variable:

$ token=${var:17:36}
$ echo "$token"
ox jumped over the lazy dog on the w

Or:

$ token=$(cut -c 18-53 <<<"$var")
$ echo "$token"
ox jumped over the lazy dog on the w

POSIX

The above commands work in bash. If we want portability to POSIX shells, then we can use neither substring expansion nor here strings. Instead, as Gordon Davisson points out, we can use:

$ echo "$var" | cut -c 18-53
ox jumped over the lazy dog on the w

or:

$ token=$(echo "$var" | cut -c 18-53)
$ echo "$token"
ox jumped over the lazy dog on the w

gniourf_gniourf suggests yet another POSIX method, this one avoiding external processes:

$ printf '%.36s\n' "${var#?????????????????}"
ox jumped over the lazy dog on the w

Comparison of cut and bash substring expansion

As David C. Rankin points out in the comments, there are strong advantages to uses bash's internal string handling. One is that the use of bash's internal commands avoids the spawning of additional subshells and executables. If the additional subshells are spawned within a loop, this can greatly impact performance.

Also, command substitution has the side-effect of removing trailing newlines from its output. This can cause unwanted surprises. Using bash's internal string handling avoids this side-effect.

like image 121
John1024 Avatar answered Oct 30 '25 03:10

John1024