How to get the second column from the output of a command?

My output from the command is something like this:

1540 "AB" 6 "C" 119 "D" 

The first column always has a number followed by a space, then a line with two quotes.

My goal is to get only the second column, for example:

 "AB" "C" "D" 

I intended to use <some_command> | awk '{print $2}' <some_command> | awk '{print $2}' to accomplish this. But the question is, some values ​​in the second column contain space (s), which by default is the default delimiter for awk to separate fields. Therefore, the output is corrupted:

 "A "C" "D" 

How to get the pure value of the second column (with double quotes)?

+117
shell awk ksh
Apr 21 '13 at 22:36
source share
8 answers

Or use sed and regex.

 <some_command> | sed 's/^.* \(".*"$\)/\1/' 
+27
Apr 21 '13 at 22:57
source share

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

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

or for input from a pipe

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

exit:

 AB C D 
+158
Apr 21 '13 at 22:51
source share

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

 echo '1540 "AB"' | cut -d' ' -f2- 

-d is the delimiter, -f is the cutting field, and with -f2, we intend to cut the second field until the end.

+72
Jul 30 '13 at 9:41
source share

This should work to get a specific column from the output of the docker image command:

 REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu 16.04 12543ced0f6f 10 months ago 122 MB ubuntu latest 12543ced0f6f 10 months ago 122 MB selenium/standalone-firefox-debug 2.53.0 9f3bab6e046f 12 months ago 613 MB selenium/node-firefox-debug 2.53.0 d82f2ab74db7 12 months ago 613 MB docker images | awk '{print $3}' IMAGE 12543ced0f6f 12543ced0f6f 9f3bab6e046f d82f2ab74db7 

This will print the third column.

+28
May 03 '17 at 15:03
source share

You do not need awk for this. Using read in a Bash shell should be sufficient, for example

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

or

 while read c1 c2; do echo $c2; done < in.txt 
+14
Apr 10 '16 at 2:27
source share

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

 $ awk '{print $1}' FPAT='"[^"]+"' file "AB" "C" "D" 
+10
Apr 22 '13 at 8:47
source share
 awk -F"|" '{gsub(/\"/,"|");print "\""$2"\""}' your_file 
0
Apr 22 '13 at 8:53 on
source share
 #!/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, suppose you name the script as co, say something like this to get the file sizes (in the example, it is assumed that you are using Linux, but the script itself is OS independent): -

ls -lh | co 5

0
May 7, '19 at 9:02
source share



All Articles