How to sort on column for rows containing a certain word

前端 未结 4 958
耶瑟儿~
耶瑟儿~ 2021-02-02 18:32

I want to sort on a certain column only for rows containing a certain word. I don\'t want to see rows not containing that word. For example I have this text file:



        
相关标签:
4条回答
  • 2021-02-02 18:40

    Sort by 2nd column by selecting it in visual mode (e.g. Control+v), then run:

    !sort
    

    or to sort by 3rd column

    sort -k 3 
    

    or

    :sort /.*\%3v/
    

    Alternatively select the lines you wish to sort using the Shift+V command. Then enter

    !sort -k 3n
    

    or use the below code to tell Vim to skip the first two words in every line and sort on whatever follows:

    :%sort /^\S\+\s\+\S\+\s\+/ 
    

    or i.e. sort by 8th line:

    :sort /.*\%55v/
    

    The 'virtual' specification is the absolute number of column , which treats spaces + tabs as single character (shortly, it doesn't count tabs as eight spaces),

    so to sort by last column:

    :%sort /\<\S\+\>$/ r
    
    0 讨论(0)
  • 2021-02-02 18:53

    2 vim commands:

    :v/sdf/d
    :sort n /[^[:digit:]]*/
    
    • first deletes all lines that do not contain 'sdf'
    • second sorts numbers ignoring non-numbers
    0 讨论(0)
  • 2021-02-02 18:58

    Maxim Kim has already given an excellent answer and I was going to add this in a comment, but it just got too complicated so I'll stick it in an answer:

    You could simplify the pattern by using:

    :v/sdf/d
    sort n /\D*/
    

    as \D is equivalent to [^[:digit:]] and is a lot less typing. For more information, see

    :help \D
    

    To match on the third field specifically, rather than just the first digit, use

    :sort n /\(\S\+\s+\)\{2}/`
    

    or

    :sort n /\v(\S+\s+){2}/
    

    See:

    :help :sort
    :help \S
    :help \s
    :help pattern.txt
    :help \v
    

    As an aside, some find it easier to remember :g!/sdf/d, which does the same as :v/sdf/d - :g! is the opposite of :g and is identical to :v.

    :help :v
    :help :g
    
    0 讨论(0)
  • 2021-02-02 18:59

    Pipe your input to an external command:

    :%!grep sdf | sort -n -k3
    

    Details:

    1. select the whole content using '%'
    2. pipe it to an external command using '!'
    3. grep onyl the lines containing 'sdf'
    4. sort these lines numerically (-n) on the third field (-k3)
    0 讨论(0)
提交回复
热议问题