How do I divide the output of a command by two, an

2019-05-17 10:32发布

问题:

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 do it?

I know its simply not the case of

$middle=$(cat file | wc -l)/2

so how would i do it?

回答1:

middle=$((`wc -l < file` / 2))


回答2:

middle=$((`wc -l file | awk '{print $1}'`/2))


回答3:

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))


回答4:

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?



回答5:

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"


标签: bash unix shell