3

I tried to write a program to see if the count divisible by 2 without a remainder Here is my program

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

This program doesnt work its every time enter to the true

Aviel Ovadiya
  • 69
  • 1
  • 2
  • 10

4 Answers4

5

In the shell, the [ command does different things depending on how many arguments you give it. See https://www.gnu.org/software/bash/manual/bashref.html#index-test

With this:

[ $count%2==0 ]

you give [ a single argument (not counting the trailing ]), and in that case, if the argument is not empty then the exit status is success (i.e. "true"). This is equivalent to [ -n "${count}%2==0" ]

You want

if [ "$(( $count % 2 ))" -eq 0 ]; then

or, if you're using bash

if (( count % 2 == 0 )); then
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

Some more "exotic" way to do this:

count=0
files=(file1 file2 file3)
num=${#files[@]}

while IFS= read -r line; do
    printf '%s\n' "$line" >> "${files[count++ % num]}"
done < input_file

This will put 1st line to file1, 2nd line to file2, 3rd line to file3, 4th line to file1 and so on.

PesaThe
  • 7,259
  • 1
  • 19
  • 43
0

awk to the rescue!

what you're trying to do is a one-liner

$ seq 10 | awk '{print > (NR%2?"file1":"file2")}'

==> file1 <==
1
3
5
7
9

==> file2 <==
2
4
6
8
10
karakfa
  • 66,216
  • 7
  • 41
  • 56
-1

try

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

You have to use the $(( )) around a mod operator as well.

How to use mod operator in bash?

This will print "even number":

count=2;
if [ $(($count % 2)) == 0 ]; then
    printf "even number";
else
    printf "odd number";
fi

This will print "odd number":

count=3;
if [ $(($count % 2)) == 0 ]; then
    printf "even number";
else
    printf "odd number";
fi
pilotandy
  • 89
  • 4