How would I make an equivalent of this PHP line in bash?

596

Here is the PHP line:

intval(substr($strIn,$i, 2), 32);

I'm trying to convert this to bash, first I know thatintval is not needed because of how bash handles variables, so I don't need the first part, however I have read aboutsubstr, but I can't figure out what it does in this case. Does anyone know what the equivalent in bash would be?

304

Answer

Solution:

PHP is loosely typed; there are few occasions you'd need to explicitly convert a string to an integer with . But, one of those occasions is if you're using a different radix. Note the second parameter tointval() is 32, meaning it's being converted from base 32. Of course, bash can also do this:

strIn=foobar
i=2
echo $((32#${strIn:$i:2}))

Note this is using bash-specific base conversion and won't necessarily work in other shells.

Test results:

mike ~ $ php -a
Interactive shell

php > $strIn = 'foobar';
php > $i = 4;
php > echo intval(substr($strIn,$i, 2), 32);
347
php > exit
mike ~ $ strIn="foobar"
mike ~ $ i=4
mike ~ $ echo $((32#${strIn:$i:2}))
347
mike ~ $ 
442

Answer

Solution:

Another way to achieve this is using cut:

substr($strIn, $i, $length) equivalent:

end=$(expr $i + $length)
echo $strIn | cut -b $i-$end

People are also looking for solutions to the problem: java - error parsing data from mysql database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.