I'd like to view a text file on the terminal and highlight its numbers. Something like I get when I open it with gedit
.
I haven't been able to do this with less
, cat
, vim
or other viewers/editors.
P.S. My question is straightforward, but I haven't been able to find the correct keywords for a meaningful search.
DIY solution
Solution A
Match every number and highlights it, print every line:
egrep --colour=always '[-+]?[0-9]*[\.e]?[0-9]|$'
I guess I'll simply alias this.
I'm still wondering if there's a default option.
Edit: adding support for exponential e
, tnx to @αғsнιη.
Solution B
Alright, my final solution below
grep -P --colour=always '(?:^|(?<=[\\, ;\-\+\*\/]))[-+]?[0-9]*[\.eE]?[0-9]+|$'
It looks behind for separation characters or beginning of line, and matches a great deal of number formats and the end of the line (so that every line is printed).
Finally, two useful aliases v
iew and l
ess-v
iew:
alias v="grep --colour=always -P '(?:^|(?<=[\\, ;\-\+\*\/]))[-+]?[0-9]*[\.eE]?[0-9]+|$'"
function lv {
v $1 | less -R
}
Solution C
Here a better regex expression (to use within the single quotes of Solution B):
(?<![\w\.])[-+]?[0-9]*[\.eE]?\-?[0-9]+|$
This solution accounts for any non alphanumeric and dot separation symbols.
The previous one was lacking of generality.
Edit: adding -nT
to grep
shows aligned line numbers.
Edit2: account for negative exponents by adding \-?
.
TL;DR
Paste this in your ~/.bashrc
and use the v
, lv
, cv
to view, less-view, and column-view your text files:
# Highlight numbers when displaying text files
alias v="grep --colour=always -nTP '(?<![\w\.])[-+]?\-?[0-9]*[\.eE]?[0-9]+|$'"
# Send v output to less
function lv {
v $1 | less -R
}
# Convert CSV to TSV and send to lv
function cv {
column -ts, $1 | lv
}
Edit: add CSV file reading shortcut and comments.
Best Answer
Match also +/- signs and
e
as well.This will match below various of numbers.