KP65
KP65

Reputation: 13585

How do I divide the output of a command by two, and store the result into a bash variable?

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?

Upvotes: 7

Views: 16078

Answers (5)

Dennis Williamson
Dennis Williamson

Reputation: 360153

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

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342463

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"

Upvotes: 0

jonescb
jonescb

Reputation: 22771

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?

Upvotes: 0

blahdiblah
blahdiblah

Reputation: 34011

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

Upvotes: 16

Steve Emmerson
Steve Emmerson

Reputation: 7832

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

Upvotes: 2

Related Questions