Reputation: 422
I have a file with contents:
$> cat file
1
2
4
Now, I would like to use/run another script, if the differences between the numbers (subtraction) is larger than 1, else exit from the main script.
I tried to do this in the following way, but does not work:
less file \
| awk '\
function abs(x){return (((x < 0.0) ? -x : x) + 0.0)}\
BEGIN{i=1;}\
{new=old;old=$1}\
{if(abs($1-new)>1)i++;}
END{if(i>1) print 1; else print 0;}' \
| while read i;do
if (( ${i} ));then
echo -n "Would you like to continue? [yes or no]: "
read yno
case ${yno} in
y )
echo Continuing...
;;
n )
echo Exiting...
;;
* )
echo "Invalid input"
;;
esac
else echo Cont...
fi
done
I would expect, that if ${i}==1, then I can make a decision, whether I want to continue or not.
Upvotes: 1
Views: 75
Reputation: 37278
you wrote
I would expect, that if ${i}==1,
Yes, but what if ${i} = "Error on input" or some other value, your statement needs to explicitly state your condition. Also using less to send a file to a pipe is not a standard situation, why not just pass in the filename to awk for processing, i.e.
awk '\
function abs(x){return (((x < 0.0) ? -x : x) + 0.0)}\
BEGIN{i=1;}\
{new=old;old=$1}\
{if(abs($1-new)>1)i++;}
END{if(i>1) print 1; else print 0;}' file1 \
| while read i;do
if (( "${i}" == 1 ));then
echo -n "Would you like to continue? [yes or no]: "
read yno
. . .
I hope this helps
Upvotes: 1
Reputation: 11543
The problem is that the only input is from less which is fully consumed by the awk script. The console is not available.
Would something like this be useful
i=$(awk 'function abs(x){return (((x < 0.0) ? -x : x) + 0.0)}BEGIN{i=1;}{new=old;old=$1}{if(abs($1-new)>1)i++;}END{if(i>1) print 1; else print 0;}' file)
if (( ${i} ));then
echo -n "Would you like to continue? [yes or no]: "
read yno
case ${yno} in
y )
echo Continuing...
;;
n )
echo Exiting...
;;
* )
echo "Invalid input"
;;
esac
else echo Cont...
fi
Upvotes: 0