0

Example:

Known Data: Total population = "150"

Question: Using bash how can I find out the number of characters within quotes? and assign that output to a variable?

  • Just one occurrence of "string"? – Jacob Vlijm Aug 31 '18 at 11:09
1

As you mentioned in bash and assuming there is a single occurrence of "string", you could do:

str='Known Data: Total population = "150"'
strip=${str/\"*\"/}
len=$(( ${#str} - ${#strip} -2 ))

then:

echo $len
3
4

Using grep:

var=$(grep -Po '(?<=").*(?=")' fileName | tr -d '\n' | wc -c)

for your example returns:

echo $var
3

Using sed:

var=$(sed -r 's/^.*"(.*)".*/\1/' fileName | tr -d '\n' | wc -c)
  • If i were to simply Echo the statement first, is it possible to count the characters and output the value? the reason why i ask this is , there might be many instances of quoted text in a file, i have to identify a particular pattern, in this case 'Total population = ' and then find the next immediate quoted text and count the number of characters in it. – Sai Varun Aug 31 '18 at 11:55
  • @SaiVarun Yes. You can echo the line too: var=$( echo 'line bla bal "494" foo bar' | grep ... ). – Ravexina Aug 31 '18 at 12:02
4

Using awk:

string='Known Data: Total population = "150"'
var=$(awk -F\" '{print length($2)}' <<< "$string")
1

Using perl:

One/first match per line:

perl -ne '{ print; m/"(.*?)"/; print length($1),"\n"; }'

Multiple matches per line:

perl -ne '{ print; while (m/"(.*?)"/g) { print length($1),"\n"; } }'

Your example:

echo 'Known Data: Total population = "150"' | \
    perl -ne '{ print; m/"(.*?)"/; print length($1),"\n"; }'

Known Data: Total population = "150"
3

Example with 2 quoted strings:

echo 'Known Data: Total population = "150"
Two quoted strings: "70" and "6000"' | \
perl -ne '{ print; while (m/"(.*?)"/g) { print length($1),"\n"; } }'

Known Data: Total population = "150"
3
Two quoted strings: "70" and "6000"
2
4

Leave out the print; if you don't need the original line printed.

e.g.:

var=$(echo 'Known Data: Total population = "150"' | \
        perl -ne '{ m/"(.*?)"/; print length($1),"\n"; }')
echo $var
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.