Split output of command by columns using Bash?

前端 未结 10 854
遥遥无期
遥遥无期 2020-12-23 02:46

I want to do this:

  1. run a command
  2. capture the output
  3. select a line
  4. select a column of that line

Just as an example, l

相关标签:
10条回答
  • 2020-12-23 03:13

    I think the simplest way is to use awk. Example:

    $ echo "11383 pts/1    00:00:00 bash" | awk '{ print $4; }'
    bash
    
    0 讨论(0)
  • 2020-12-23 03:23

    Similar to brianegge's awk solution, here is the Perl equivalent:

    ps | egrep 11383 | perl -lane 'print $F[3]'
    

    -a enables autosplit mode, which populates the @F array with the column data.
    Use -F, if your data is comma-delimited, rather than space-delimited.

    Field 3 is printed since Perl starts counting from 0 rather than 1

    0 讨论(0)
  • 2020-12-23 03:25

    Bash's set will parse all output into position parameters.

    For instance, with set $(free -h) command, echo $7 will show "Mem:"

    0 讨论(0)
  • 2020-12-23 03:31

    try

    ps |&
    while read -p first second third fourth etc ; do
       if [[ $first == '11383' ]]
       then
           echo got: $fourth
       fi       
    done
    
    0 讨论(0)
  • 2020-12-23 03:31

    Your command

    ps | egrep 11383 | cut -d" " -f 4
    

    misses a tr -s to squeeze spaces, as unwind explains in his answer.

    However, you maybe want to use awk, since it handles all of these actions in a single command:

    ps | awk '/11383/ {print $4}'
    

    This prints the 4th column in those lines containing 11383. If you want this to match 11383 if it appears in the beginning of the line, then you can say ps | awk '/^11383/ {print $4}'.

    0 讨论(0)
  • 2020-12-23 03:31

    Instead of doing all these greps and stuff, I'd advise you to use ps capabilities of changing output format.

    ps -o cmd= -p 12345
    

    You get the cmmand line of a process with the pid specified and nothing else.

    This is POSIX-conformant and may be thus considered portable.

    0 讨论(0)
提交回复
热议问题