Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

grep

bash

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?

like image 852
micobg Avatar asked May 07 '12 17:05

micobg


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

re="^ *([0-9]+)" && [[ "$(wc -c f1.txt)" =~ $re ]] && echo "${BASH_REMATCH[1]}"
like image 108
anubhava Avatar answered Oct 06 '22 00:10

anubhava


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

like image 30
glenn jackman Avatar answered Oct 06 '22 00:10

glenn jackman