!/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 ?
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
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
cut and bash substring expansionAs 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With