views:

176

answers:

5

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  A: 
middle=$((`wc -l file | awk '{print $1}'`/2))
Steve Emmerson
I'd prefer not to use awk to be honest, there is a way to do it without it, im just reading a book and it says not to use sed or awk
KP65
the above command can be done without `wc`. just `awk` will do.
ghostdog74
+5  A: 
middle=$((`wc -l < file` / 2))
We have a winner. And just as I got back from reading the man page, too. (I generally script to vanilla /bin/sh, so I always have to look up bashisms)
dmckee
@blahdiblah: Did you notice how the OP used `$()` instead of backticks? Also, it's good that you corrected the useless use of `cat`, but then you replaced it with a useless use of redirection. `wc` accepts filenames as arguments. Also, `wc` outputs the filename which needs to be stripped off before you can do the division.
Dennis Williamson
@dennis, the redirection has a "purpose". It eliminates the file name, giving just the number of line count.
ghostdog74
A: 

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?

jonescb
See the `Arithmetic Expressions` section of the man page.
dmckee
A: 

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"
ghostdog74
A: 

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))
Dennis Williamson
`wc -l < file` gets just the number of line count. FYI.
ghostdog74
@ghostdog74: Thanks.
Dennis Williamson