How to shorten my code?


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers How to shorten my code?
# 1  
Old 11-07-2013
How to shorten my code?

Code:
salary_range_report()
{
	echo -e ${underline}$redYellow"\nSalary Range Report\n"
	tput sgr0

	count_0_to_999=0
	count_1000_to_2999=0
	count_2000_to_5999=0
	count_6000_to_9999=0
	count_10000_above=0

	for i in `cut -d "," -f4 $PAYROLL` #Loop Salary
	do
		if [ $i -lt "999" ] && [ $i -gt "0" ]
		then
			let "count_0_to_999 = count_0_to_999 + 1"
		elif [ $i -gt "1000" ] && [ $i -lt "2999" ]
		then
			let "count_1000_to_2999 = count_1000_to_2999 + 1"
		elif [ $i -gt "2000" ] && [ $i -lt "5999" ]
		then
			let "count_2000_to_5999 = count_2000_to_5999 + 1"
		elif [ $i -gt "6000" ] && [ $i -lt "9999" ]
		then
			let "count_6000_to_9999 = count_6000_to_9999 + 1"
		else
			let "count_10000_above = count_10000_above + 1"
		fi
	done

	echo -e "Salary Range\t\tTotal"
	echo -e "\$0 -999\t\t\t$count_0_to_999"
	echo -e "\$1000 -2999\t\t$count_1000_to_2999"
	echo -e "\$2000 -5999\t\t$count_2000_to_5999"
	echo -e "\$6000 -9999\t\t$count_6000_to_9999"
	echo -e ">\$10,000\t\t$count_10000_above"
	
	
	echo -en "Hit [Enter] to return to main menu..."
   	read
}

Hi there everyone, as my title stated, how can i shorten my code? Im new to shell scripting and i think my code can be shorten to just a line.
My code is working perfectly and able to generate a report.
I saw people using awk utility and just one line , they are doing the same thing as my long code above.

So i hope someone could help me start up with the awk so i can see if im able to work out with it
Thank you guys!
# 2  
Old 11-07-2013
Well then...now is the time to start reading this book...
# 3  
Old 11-07-2013
Quote:
Originally Posted by eggisbad
Hi there everyone, as my title stated, how can i shorten my code? Im new to shell scripting and i think my code can be shorten to just a line.
You don't want to "shorten your code" - you want to shorten the time it needs to get executed. This is sometimes, but not always the same.

First thing you should do in your code is straighten it out:

Code:
	for i in `cut -d "," -f4 $PAYROLL` #Loop Salary

You should NOT do this: you should not use a "for"-loop for a possibly long list, because the expansion will let the resulting line (after evaluation of the backticks) grow and shell command lines have a certain maximum length (see the "MAX_LIN" kernel constant). Further, you should not use the backticks at all, because they are deprecated. Use a simple pipeline with a while-loop:

Code:
	cut -d "," -f4 $PAYROLL | while read i ; do

Another point is: let. You havent't told us which shell you use, but you do not need "let" any more in any modern bourne-descending shell (ksh, bash, ...). Instead of

Code:
let "count_0_to_999 = count_0_to_999 + 1"

simply write

Code:
(( count_0_to_999 += 1 ))

Last hint: you start comparing at the bottom and therefore you have always two tests to perform to find out if a value is within a certain range. Start at the top and you have only one test. Pseudo-code:

Code:
if salary > 10000
     count_above_10000 += 1
elif salary >= 6000
     count_6000_to_9999 += 1
elif salary >= 2000
     count_5999_to_2000 += 1
elif salary >= 1000
     count_1999_to_1000 += 1
elif salary > 0
     count_999_to_0 += 1
else
     print "Error: we should never arrive here."
fi

A last point: typecast your variables before you use them:
Code:
typeset -i count_0_to_999=0
typeset -i count_1000_to_2999=0
typeset -i count_2000_to_5999=0
typeset -i count_6000_to_9999=0
typeset -i count_10000_above=0

# 4  
Old 11-08-2013
Another way to do the loop, that would not involve the cut statement:
Code:
while IFS=, read _ _ _ i _
do

done < "$PAYROLL"



--
Quote:
Originally Posted by bakunin
[..] you should not use a "for"-loop for a possibly long list, because the expansion will let the resulting line (after evaluation of the backticks) grow and shell command lines have a certain maximum length (see the "MAX_LIN" kernel constant).
The for loop is an internal compound shell command that is part of the shell syntax and it does not suffer from these limits..

Quote:
There shall be no limit on the size of any shell command other than that imposed by the underlying system (memory constraints, {ARG_MAX}, and so on).
Shell Commands

ARG_MAX is the maximum length of arguments for a new process and that is not the case here.

Even in cases where the shell calls an external program and tries to pass too many elements, then it is not the shell that imposes this limit. It only delivers the error message...
# 5  
Old 11-08-2013
Not sure if that overlap (1999 vs 2999) is mandatory or just a typo.
I'm pretty sure that one calculation is faster than five comparisons, so try sth like
Code:
((BIN[i/1000]++))

in your loop, and then output e.g. BIN[0], BIN[1]+BIN[2] etc. finally
 
Login or Register to Ask a Question

Previous Thread | Next Thread

7 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Shorten header of protein sequences in fasta file to only organism name

I have a fasta file as follows >sp|Q8WWQ8|STAB2_HUMAN Stabilin-2 OS=Homo sapiens OX=9606 GN=STAB2 PE=1 SV=3 MMLQHLVIFCLGLVVQNFCSPAETTGQARRCDRKSLLTIRTECRSCALNLGVKCPDGYTM ITSGSVGVRDCRYTFEVRTYSLSLPGCRHICRKDYLQPRCCPGRWGPDCIECPGGAGSPC NGRGSCAEGMEGNGTCSCQEGFGGTACETCADDNLFGPSCSSVCNCVHGVCNSGLDGDGT... (3 Replies)
Discussion started by: jerrild
3 Replies

2. Shell Programming and Scripting

Ps command and awk - shorten characters

ps -e -o pcpu -o pid -o user -o args | sort -k 1 | tail -6r %CPU PID USER COMMAND 0.3 223220 root /usr/tivoli/tsm/client/ba/bin/dsmc sched 0.2 411332 root /usr/sbin/syslogd 0.1 90962 root /usr/sbin/syncd 60 0.0 10572 root -ksh 0.0 94270 root -ksh ... (4 Replies)
Discussion started by: SkySmart
4 Replies

3. Shell Programming and Scripting

Shorten header of protein sequences in fasta file

I have a fasta file as follows >sp|O15090|FABP4_HUMAN Fatty acid-binding protein, adipocyte OS=Homo sapiens GN=FABP4 PE=1 SV=3 MCDAFVGTWKLVSSENFDDYMKEVGVGFATRKVAGMAKPNMIISVNGDVITIKSESTFKN TEISFILGQEFDEVTADDRKVKSTITLDGGVLVHVQKWDGKSTTIKRKREDDKLVVECVM KGVTSTRVYERA >sp|L18484|AP2A2_RAT AP-2... (3 Replies)
Discussion started by: alexypaul
3 Replies

4. UNIX for Dummies Questions & Answers

How can i use function for the below script to shorten it?

Hi All, i worte a shell script which will zcat the .gz file and write it in to a tmp file and then again cat the file and convert it to Dos mode. Next step is i am greping the file to search for the particular string on the 1st line and if the string does not exits it will insert the 1st line... (1 Reply)
Discussion started by: vikatakavi
1 Replies

5. Shell Programming and Scripting

Block of code replacement in Java source code through Unix script

Hi, I want to remove the following code from Source files (or replace the code with empty.) from all the source files in given directory. finally { if (null != hibernateSession && hibernateSession.isOpen()) { //hibernateSession.close(); } } It would be great if the script has... (2 Replies)
Discussion started by: hareeshram
2 Replies

6. Shell Programming and Scripting

script to shorten usernames and output to file

Hopefully someone here can point me in the correct direction. I'm working on a username migration and am trying to map my users ols usernames to the new ones. Right now every user has a username of firstname.lastname i.e. john.doe I'm trying to create a bash or python script that will take... (3 Replies)
Discussion started by: binary-ninja
3 Replies

7. Shell Programming and Scripting

Howto shorten script in a busybox environment by using for loops?

My satellite receiver is equipped with busybox, so a small linux version. That is why I can not use certain commands like #tomorrow in date commands or #date -d &quot;+1 day&quot; and thus I have to use: day1=$ I want to download every day 6 files from the internet but the filenames consist of the date... (6 Replies)
Discussion started by: ni_hao
6 Replies
Login or Register to Ask a Question