[英]convert a filename eg file01010101 from decimal to binary using two's complement, without using built in binary function in bash
這是 shell 腳本的二進制評估和轉換部分。
elif [[ $file == file[0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1] ]]
then
first=`echo $file | cut -c 5`
second=`echo $file | cut -c 6`
third=`echo $file | cut -c 7`
fourth=`echo $file | cut -c 8`
fifth=`echo $file | cut -c 9`
sixth=`echo $file | cut -c 10`
seventh=`echo $file | cut -c 11`
eighth=`echo $file | cut -c 12`
newname=file`expr $first \* 128 + $second \* 64 + $third \* 32 + $fourth \* 16 + $fifth \* 8 + $sixth \* 4 + $seventh \* 2 + $eighth \* 1` #this is converting the binary into decimal one bit at a time starting from the leftmost number
while [ ! -d CATEGORY1 ]
do
mkdir CATEGORY1
done
mv $1/$file CATEGORY1/$newname
echo "renamed - $file (now named $newname) so it has been moved to the CATEGORY1 directory."
這就是我所擁有的,但它不包含二進制補碼,我不能使用 bash 的內置二進制特性。
我不能使用 bash 的內置二進制功能
我不確定它是什么意思,算術表達式?
首先,為了簡化一點,我將使用 bash 正則表達式來捕獲二進制數:
if [[ $file =~ ^file([01]{8})$ ]]
then
你只需要以你喜歡的任何方式轉換它:
newname=file$((2#${BASH_REMATCH[1]})) # bash builtin conversion
# or
newname=file$(echo "ibase=2;${BASH_REMATCH[1]}" | bc) # POSIX conversion
對於二進制補碼,您可以執行以下操作:
if [[ ${BASH_REMATCH[1]} == 1* ]]
then
echo "ibase=2; - ( $(tr 10 01 <<< "${BASH_REMATCH[1]}") + 1)"
else
echo "ibase=2; ${BASH_REMATCH[1]}"
fi | bc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.