English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am using the bourne scripting langauge and would like to be able to set the "wc -l" (line count) as a variable in my script. can this be done?

I want to be able to make a for loop ranging from one going until the value returned as the line count. i tried
for ((i=1;i=wc -l;i=i+1))

but it doesnt seem to work. the logical conclusion is that i need to set the value which would be returned from the wc -l command as a variable.

Thanks in advance--AJ

2007-08-13 09:29:09 · 1 answers · asked by toodles_1399 1 in Computers & Internet Programming & Design

1 answers

foo.sh content:

#/bin/sh

MY_VAR=`wc -l foo.sh | awk '{print $1}'`
echo MY_VAR = $MY_VAR

for (( i=1; $i<=$MY_VAR; i=$i+1 )); do
echo "i = $i" ;
done

====================
Sample output:

wolf:1058:~$ ./foo.sh
MY_VAR = 8
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8

===================
Notes:

I do "wc -l foo.sh", to count the lines in a specific file. I use the same script I'm testing with as the line-count file, but you'd want to use whatever other file you want to count the lines of.

awk '{print $1}' peels off the first "word" from the sole line of output of wc -l, and uses that. The output of wc -l foo.sh is something like "8 foo.sh" and the awk statement strips that down to just "8". It's possible to use the shell's built-in parameter parsing ("the first word in variable X") but off the top of my head I couldn't remember how.

2007-08-13 10:11:41 · answer #1 · answered by McFate 7 · 0 0

fedest.com, questions and answers