How to get the second column from command output?

后端 未结 8 1123
有刺的猬
有刺的猬 2020-11-29 18:08

My command\'s output is something like:

1540 \"A B\"
   6 \"C\"
 119 \"D\"

The first column is always a number, followed by a space, then a

相关标签:
8条回答
  • 2020-11-29 18:16

    Use -F [field separator] to split the lines on "s:

    awk -F '"' '{print $2}' your_input_file
    

    or for input from pipe

    <some_command> | awk -F '"' '{print $2}'
    

    output:

    A B
    C
    D
    
    0 讨论(0)
  • 2020-11-29 18:19
    #!/usr/bin/python
    import sys 
    
    col = int(sys.argv[1]) - 1
    
    for line in sys.stdin:
        columns = line.split()
    
        try:
            print(columns[col])
        except IndexError:
            # ignore
            pass
    

    Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

    ls -lh | co 5

    0 讨论(0)
  • 2020-11-29 18:24

    If you could use something other than 'awk' , then try this instead

    echo '1540 "A B"' | cut -d' ' -f2-
    

    -d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.

    0 讨论(0)
  • 2020-11-29 18:24

    You don't need awk for that. Using read in Bash shell should be enough, e.g.

    some_command | while read c1 c2; do echo $c2; done
    

    or:

    while read c1 c2; do echo $c2; done < in.txt
    
    0 讨论(0)
  • 2020-11-29 18:31

    If you have GNU awk this is the solution you want:

    $ awk '{print $1}' FPAT='"[^"]+"' file
    "A B"
    "C"
    "D"
    
    0 讨论(0)
  • 2020-11-29 18:33

    Or use sed & regex.

    <some_command> | sed 's/^.* \(".*"$\)/\1/'
    
    0 讨论(0)
提交回复
热议问题