'c' shell scripts

stan at teltone.UUCP stan at teltone.UUCP
Sun Dec 18 06:17:52 AEST 1983


# Here's 3 ways of indexing through a file's contents within a
# C shell script.  Assume the file name is "file".
# (you can even write all the below to some file and run csh on it)
#=================================================

echo "Method 1"
set f = ("`cat file`")	# makes f a list of elements, each being a line of file

# foreach line ($f)	# note that you can't do it with this foreach loop.
# 	echo "$line"
# end

@ linenum = 1
while ($linenum <= $#f)
 	echo "$f[$linenum]" # gets each line, including embedded white space.
 	# echo $f[$linenum]   # gets each line, embedded white space collapses
			    # to single spaces.
	@ linenum++
end

	# echo "$f[1]"	# gets the first line of the file
	# echo "$f[$#f]"	# gets the last line of the file
#------------------------------
# limitation on above is the length of the file. (approx. 10,290 bytes)
#=====================================================

echo "Method 2"
set linecount = `wc -l < file`		# have to use '<' here.
@ linenum = 1
while ($linenum <= $linecount)
	set line = "`awk 'NR == $linenum  {print;exit}' file`"
		    # above makes $line have a single string value.
			# note: $linenum will be expanded properly
	echo "$line"
	@ linenum++
end

#======================================================
# similar to above, but use 'sed', which might be (and probably is) faster
# than awk.

echo "Method 3"
set linecount = `wc -l < file`
@ linenum = 1
while ($linenum <= $linecount)

    # 2 backslashes at end of each of next 2 lines
set line = "`sed -n '$linenum{p\\
q\\
}' file`"
		# can't put comments after 2 lines with backslashes above
echo "$line"
@ linenum++

end

##### Whew!  Took a while to make all this to work, especially since I've
##### never required the csh to do this.



More information about the Comp.unix mailing list