Answer to Question #292722 in UNIX/Linux Programming for Lavu

Question #292722

Write a shell script that, given a file name as the argument will write the even numbered line to a file with name even file and odd numbered lines in a text file called odd file.



1
Expert's answer
2022-02-02T08:19:40-0500
file=$1
counter=0
 
eout="evenfile.$$" # even file name
oout="oddfile.$$" # odd file name
 
if [ $# -eq 0 ] 
then
	echo "$(basename $0) file"
	exit 1 
fi
 
if [ ! -f $file ]
then
	echo "$file not a file"
	exit 2
fi
 
while read line
do
	# find out odd or even line number 
	isEvenNo=$( expr $counter % 2 )
 
	if [ $isEvenNo -ne 0 ] 
	then
		# even match
		echo $line >> $eout
	else
		# odd match
		echo $line >> $oout	
	fi
	# increase counter by 1
	(( counter ++ ))
done < $file
echo "Even file - $eout"
echo "Odd file - $oout"

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS