In: Computer Science
Can you write the shell scripts for these C files (code in C):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argb, char *argv[]){
char ch;
int upper=1;
if(argb>1){
if(strcmp(argv[1],"-s")==0){
upper=1;
}
else if(strcmp(argv[1],"-w")==0){
upper=0;
}
}
while((ch=(char)getchar())!=EOF){
if(upper){
printf("%c",toupper(ch));
}
else{
printf("%c",tolower(ch));
}
}
return 0;
}
========================================================
#include <stdio.h>
#include <stdlib.h>
int calcRange(int array[],int size){
int max=array[1];
int min=array[0];
int a=0;
for(a=1;a<size;a++){
if(array[a]>max){
max=array[a];
}
}
for(a=1;a<size;a++){
if(array[a]<min){
min=array[a];
}
}
printf("%d-%d=%d\n",max,min,max-min);
}
int main(int arga, char **argv){
int i;
if(arga>1){
int array[arga];
for(i=1;i<arga;i++){
array[i]=atoi(argv[i]);
}
int range=calcRange(array,arga);
printf("range=%d\n",range);
}
}
Please find the requested scripts below.
Please provide your feedback
Thanks and Happy learning!
#!/bin/bash
#Above line sets the environment for the script to bash
#Check for the command line argument
if [ $# -eq 1 ]
then
if [ "$1" == "-s" ]
then
upper=1;
elif [ "$1" == "-w" ]
then
upper=0;
else
echo "Invalid argument $1. Valid values are -s and -w"
exit 0
fi
else
echo "There should be exactly one command line argument. Valid argument values are -s or -w"
exit 0;
fi
#Press ctrl D for EOF character
while read ch
do
if [ $upper -eq 1 ]
then
#Convert the character to upper case
echo `echo "$ch" | tr [a-z] [A-Z]`
else
#Convert the character to lower case
echo `echo "$ch" | tr [A-Z] [a-z]`
fi
done
#!/bin/bash
#Above line sets the environment for the script to bash
calcRange()
{
# Shift all arguments to the left (original $1 gets lost)
shift;
# Rebuild the array after excluding the first argument(ie array size)
arr=("$@")
max=${arr[1]}
min=${arr[0]}
#find the max element from the array
for i in "${arr[@]}"
do
if [ $i -gt $max ]
then
max=$i
fi
done
#find the min element from the array
for j in "${arr[@]}"
do
if [ $j -lt $min ]
then
min=$j
fi
done
range=`expr $max - $min`
echo "$max-$min=$range"
}
#Check for the command line argument
if [ $# -gt 1 ]
then
k=0;
for i in $@
do
myArr[k]=$i
k=`expr $k + 1`
done
else
echo "There should be more than one command line argument."
exit 0;
fi
calcRange "${myArr[@]}"