Say if i wanted to do this command:
(cat file | wc -l)/2
and store it in a variable such as middle, how would i 开发者_JAVA百科do it?
I know its simply not the case of
$middle=$(cat file | wc -l)/2
so how would i do it?
middle=$((`wc -l < file` / 2))
middle=$((`wc -l file | awk '{print $1}'`/2))
This relies on Bash being able to reference the first element of an array using scalar syntax and that is does word splitting on white space by default.
middle=($(wc -l file)) # create an array which looks like: middle='([0]="57" [1]="file")'
middle=$((middle / 2)) # do the math on ${middle[0]}
The second line can also be:
((middle /= 2))
When assigning variables, you don't use the $
Here is what I came up with:
mid=$(cat file | wc -l)
middle=$((mid/2))
echo $middle
The double parenthesis are important on the second line. I'm not sure why, but I guess it tells Bash that it's not a file?
using awk.
middle=$(awk 'END{print NR/2}' file)
you can also make your own "wc" using just the shell.
linec(){
i=0
while read -r line
do
((i++))
done < "$1"
echo $i
}
middle=$(linec "file")
echo "$middle"
精彩评论