Friday, August 10, 2012

Bash Exercises I : Practice with if statements, cut, grep, arithmetic, shell arguments



There are two parts.

1)

Write a shell script that converts binary to decimal and the other way around.

Do not worry about numbers that go over 8 bits, so that means 1111111 is your highest binary number and 255 is your highest decimal number.

Here is the interface:

decbin.sh destination number

destination = b or h

Note: You do not need loops for this; this can be done with if statements.

Example-

decbin.sh b 6
110
decbin.sh b 24
11000
decbin.sh d 10101010
170


2)

Write a shell script to emulate a simplified version of the select sql statement.

select finds rows in a table and prints them based on your specifications.

For this exercise, your interface will look like this:

sqlselect.sh table condition

table = some text file (I will give you a sample one)
condition = some equality statement, such as id=1 or name=tom (there should not be any spaces around the equal sign)

The lefthandside of a condition is the field name and righthandside is the value. You only have to worry about tables having up to three fields.

A table file starts with a line that indicates the name of each field. Here is an example file
"id","name","rating"
"1","bob","7"
"2","tom","10"
"3","cal","8"
"4","betty","7"
"5","al","8"


Here are some examples-
sqlselect.sh workers.txt id=2
Output: "2","tom","10"
sqlselect.sh workers.txt name=betty
Output: "4","betty","7"
sqlselect.sh workers.txt rating=8
Output:
"3","cal","8"
"5","al","8"

In order to implement this program you are not required to use loops. You can simply get the record number of each match and feed it to this program (as a separate file). You do not have to use my program; it is just here if you need it.

printlines.sh
#!/bin/sh
#call me like this: printlines.sh "recordno1 recordno2 ..." table
#examples
#
#printlines.sh "1" workers.txt
#printlines.sh "1 2 3" workers.txt
for i in $1
do
sed -n ${i}p $2
done

No comments:

Post a Comment