micobg
micobg

Reputation: 1342

Bash: how to take a number from string? (regular expression maybe)

I want to get a count of symbols in a file.

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

But this code return a line where grep found numbers. I want to retrun only 38. How?

Upvotes: 9

Views: 12516

Answers (2)

anubhava
anubhava

Reputation: 785146

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 capabilities:

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

Upvotes: 14

glenn jackman
glenn jackman

Reputation: 246807

pass data to wc from stdin instead of a file: nchars=$(wc -c < f1.txt)

Upvotes: 8

Related Questions