使用二进制补码将文件名(例如 file01010101)从十进制转换为二进制,而无需在 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."

这是我得到的,但它不包含2的补充,我不能使用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