程序检查问题是否可以被 2 整除且没有余数 BASH
Issue with program check if the number is divisible by 2 with no remainder BASH
我试着写了个程序看看这个数能不能被2整除而没有余数
这是我的程序
count=$((count+0))
while read line; do
if [ $count%2==0 ]; then
printf "%x\n" "$line" >> file2.txt
else
printf "%x\n" "$line" >> file1.txt
fi
count=$((count+1))
done < merge.bmp
这个程序不工作它每次进入真实
尝试
count=$((count+0))
while read line; do
if [ $(($count % 2)) == 0 ]; then
printf "%x\n" "$line" >> file2.txt
else
printf "%x\n" "$line" >> file1.txt
fi
count=$((count+1))
done < merge.bmp
您还必须在 mod 运算符周围使用 $(( ))。
How to use mod operator in bash?
这将打印 "even number":
count=2;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi
这将打印 "odd number":
count=3;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi
awk
救援!
你想做的是单行
$ seq 10 | awk '{print > (NR%2?"file1":"file2")}'
==> file1 <==
1
3
5
7
9
==> file2 <==
2
4
6
8
10
在 shell 中,[
命令会根据您提供的 参数数量 执行不同的操作。参见 https://www.gnu.org/software/bash/manual/bashref.html#index-test
有了这个:
[ $count%2==0 ]
你给 [
一个 单个 参数(不包括尾随 ]
),在这种情况下,如果参数不为空,则退出状态为成功(即 "true")。这相当于 [ -n "${count}%2==0" ]
你想要
if [ "$(( $count % 2 ))" -eq 0 ]; then
或者,如果您使用的是 bash
if (( count % 2 == 0 )); then
更多"exotic"方法:
count=0
files=(file1 file2 file3)
num=${#files[@]}
while IFS= read -r line; do
printf '%s\n' "$line" >> "${files[count++ % num]}"
done < input_file
这会将第 1 行放到 file1
、第 2 行到 file2
、第 3 行到 file3
、第 4 行到 file1
等等。
我试着写了个程序看看这个数能不能被2整除而没有余数 这是我的程序
count=$((count+0))
while read line; do
if [ $count%2==0 ]; then
printf "%x\n" "$line" >> file2.txt
else
printf "%x\n" "$line" >> file1.txt
fi
count=$((count+1))
done < merge.bmp
这个程序不工作它每次进入真实
尝试
count=$((count+0))
while read line; do
if [ $(($count % 2)) == 0 ]; then
printf "%x\n" "$line" >> file2.txt
else
printf "%x\n" "$line" >> file1.txt
fi
count=$((count+1))
done < merge.bmp
您还必须在 mod 运算符周围使用 $(( ))。
How to use mod operator in bash?
这将打印 "even number":
count=2;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi
这将打印 "odd number":
count=3;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi
awk
救援!
你想做的是单行
$ seq 10 | awk '{print > (NR%2?"file1":"file2")}'
==> file1 <==
1
3
5
7
9
==> file2 <==
2
4
6
8
10
在 shell 中,[
命令会根据您提供的 参数数量 执行不同的操作。参见 https://www.gnu.org/software/bash/manual/bashref.html#index-test
有了这个:
[ $count%2==0 ]
你给 [
一个 单个 参数(不包括尾随 ]
),在这种情况下,如果参数不为空,则退出状态为成功(即 "true")。这相当于 [ -n "${count}%2==0" ]
你想要
if [ "$(( $count % 2 ))" -eq 0 ]; then
或者,如果您使用的是 bash
if (( count % 2 == 0 )); then
更多"exotic"方法:
count=0
files=(file1 file2 file3)
num=${#files[@]}
while IFS= read -r line; do
printf '%s\n' "$line" >> "${files[count++ % num]}"
done < input_file
这会将第 1 行放到 file1
、第 2 行到 file2
、第 3 行到 file3
、第 4 行到 file1
等等。