Bash: how to take a number from a string? (possibly regex)

I want to get the number of characters in a file.

wc -c f1.txt | grep [0-9]

But this code returns the string where grep found the numbers. I want to get only 38 . How?

+3
source share
2 answers

You can use awk:

wc -c f1.txt | awk '{print $1}'

OR using grep -o:

wc -c f1.txt | grep -o "[0-9]\+"

OR using bash regex features:

re="^ *([0-9]+)" && [[ "$(wc -c f1.txt)" =~ $re ]] && echo "${BASH_REMATCH[1]}"
+5
source

transfer data to wcfrom stdin instead of file:nchars=$(wc -c < f1.txt)

+5
source

All Articles