how to use sed, awk, or gawk to print only what is matched?

后端 未结 11 510
长情又很酷
长情又很酷 2021-01-30 05:59

I see lots of examples and man pages on how to do things like search-and-replace using sed, awk, or gawk.

But in my case, I have a regular expression that I want to run

11条回答
  •  长情又很酷
    2021-01-30 06:46

    If your version of grep supports it you could use the -o option to print only the portion of any line that matches your regexp.

    If not then here's the best sed I could come up with:

    sed -e '/[0-9]/!d' -e 's/^[^0-9]*//' -e 's/[^0-9]*$//'
    

    ... which deletes/skips with no digits and, for the remaining lines, removes all leading and trailing non-digit characters. (I'm only guessing that your intention is to extract the number from each line that contains one).

    The problem with something like:

    sed -e 's/.*\([0-9]*\).*/&/' 
    

    .... or

    sed -e 's/.*\([0-9]*\).*/\1/'
    

    ... is that sed only supports "greedy" match ... so the first .* will match the rest of the line. Unless we can use a negated character class to achieve a non-greedy match ... or a version of sed with Perl-compatible or other extensions to its regexes, we can't extract a precise pattern match from with the pattern space (a line).

提交回复
热议问题