我试着编写一个程序来查看计数是否可以被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
这个程序每次进入真正的
都不起作用答案 0 :(得分:1)
在shell中,[
命令会执行不同的操作,具体取决于您提供的多少参数。见https://www.gnu.org/software/bash/manual/bashref.html#index-test
有了这个:
[ $count%2==0 ]
你给[
一个单个参数(不包括尾随]
),在这种情况下,如果参数不为空,则退出状态为成功(即“真实”)。这相当于[ -n "${count}%2==0" ]
你想要
if [ "$(( $count % 2 ))" -eq 0 ]; then
或者,如果你正在使用bash
if (( count % 2 == 0 )); then
答案 1 :(得分:1)
更多“异国情调”的方式:
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 :(得分:0)
awk
救援!
你要做的是单行
$ seq 10 | awk '{print > (NR%2?"file1":"file2")}'
==> file1 <==
1
3
5
7
9
==> file2 <==
2
4
6
8
10
答案 3 :(得分:-1)
试
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?
这将打印“偶数”:
count=2;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi
这将打印“奇数”:
count=3;
if [ $(($count % 2)) == 0 ]; then
printf "even number";
else
printf "odd number";
fi