How to truncate long matching lines returned by grep or ack

前端 未结 8 1632
攒了一身酷
攒了一身酷 2020-12-13 05:38

I want to run ack or grep on HTML files that often have very long lines. I don\'t want to see very long lines that wrap repeatedly. But I do want to see just that portion of

相关标签:
8条回答
  • 2020-12-13 05:59

    I put the following into my .bashrc:

    grepl() {
        $(which grep) --color=always $@ | less -RS
    }
    

    You can then use grepl on the command line with any arguments that are available for grep. Use the arrow keys to see the tail of longer lines. Use q to quit.

    Explanation:

    • grepl() {: Define a new function that will be available in every (new) bash console.
    • $(which grep): Get the full path of grep. (Ubuntu defines an alias for grep that is equivalent to grep --color=auto. We don't want that alias but the original grep.)
    • --color=always: Colorize the output. (--color=auto from the alias won't work since grep detects that the output is put into a pipe and won't color it then.)
    • $@: Put all arguments given to the grepl function here.
    • less: Display the lines using less
    • -R: Show colors
    • S: Don't break long lines
    0 讨论(0)
  • 2020-12-13 06:05

    You could use the grep option -o, possibly in combination with changing your pattern to ".{0,10}<original pattern>.{0,10}" in order to see some context around it:

           -o, --only-matching
                  Show only the part of a matching line that matches PATTERN.
    

    ..or -c:

           -c, --count
                  Suppress normal output; instead print a count of matching  lines
                  for  each  input  file.  With the -v, --invert-match option (see
                  below), count non-matching lines.
    
    0 讨论(0)
提交回复
热议问题