Anne K.
Anne K.

Reputation: 415

Get length of string from grep does not work

I try to get the length of a string like this (bash in linux):

VAR= grep "test" file.txt
VARlength= ${#VAR}

For some reason the length is always zero, even if the string "test" is inside file.txt

Can someone explain me how to get the length of VAR and what is wrong there?

Upvotes: 0

Views: 293

Answers (3)

Kent
Kent

Reputation: 195039

  1. don't leave space before and after the =

  2. you need command substitution: var=$(command)

Upvotes: 2

cb0
cb0

Reputation: 8613

If you like it's also possbile to use bc and wc to get the result:

VARlength=$(echo "var="$(grep "2" foo | wc -c;)";--var" | bc)

This will count the chars inside the match (wc -c) and then subtract 1 using bc, because you don't want to count the newline.

Upvotes: 0

user5547025
user5547025

Reputation:

Use $( ):

VAR=$(grep "test" test.txt)
VARlength=${#VAR}

Upvotes: 1

Related Questions