简体   繁体   English

在bash中使用awk命令从记录中提取单个字段

[英]Using awk command in bash to extract a single field from a record

I want to use awk to extract a single field from a list of records. 我想使用awk从记录列表中提取单个字段。 For example, 例如,

Assignment1:/home/dir/:Admin:08-07-12
Assignment2:/home/dir/:Paul:09-22-13

I want to extract the 1st field from the second line, or the third field from the first line. 我想从第二行中提取第一个字段,或者从第一行中提取第三个字段。 Any ideas? 有任何想法吗?

awk -F: 'NR == 2 { print $1 }'
awk -F: 'NR == 1 { print $3 }'

For the given line number, print the specified field. 对于给定的行号,打印指定的字段。

It doesn't work 没用

My apologies, I am using the Bourne shell and this does not work. 抱歉,我使用的是Bourne shell,这不起作用。

As noted in the comment, I don't believe that the Bourne shell has anything directly to do with the problem. 正如评论中指出的那样,我认为Bourne shell与该问题没有任何直接关系。 (If $IFS is set to something odd, or some other peculiar setup applies, maybe that has an effect. But in a normal Bourne shell, there should be no problem.) (如果将$IFS设置为奇数,或应用某些其他特殊设置,则可能会起作用。但是在普通的Bourne shell中,应该没有问题。)

Here's what I get on my machine (an Ubuntu 14.04 derivative, but I'm confident I'd get the same result on Mac OS X 10.10.3, and pretty much any other Unix-like system, too). 这是我在计算机上获得的信息(Ubuntu 14.04衍生版,但我相信在Mac OS X 10.10.3以及几乎所有其他类似Unix的系统上也能获得相同的结果)。 This is using Bash, but I don't think that's a factor — I'll go out on a limb and say that Korn shell, Zsh, Dash, and Heirloom Shell would all work the same on this; 这是使用Bash的,但我认为这不是一个因素-我会弯腰说Korn shell,Zsh,Dash和Heirloom Shell在这方面都可以工作。 heck, it should work in the C shell family of shells too since there's nothing special about the notations used). 哎呀,它也应该在C shell壳系列中起作用,因为所使用的符号没有什么特别的)。 It is using GNU awk too, but I don't think that's a factor either. 它也使用GNU awk ,但是我也不认为这是一个因素。

$ cat data
Assignment1:/home/dir/:Admin:08-07-12
Assignment2:/home/dir/:Paul:09-22-13
$ awk -F: 'NR == 2 { print $1 }' data
Assignment2
$ awk -F: 'NR == 1 { print $3 }' data
Admin
$

The output looks like record 2, field 1 and record 1, field 3 to me. 输出对我来说就像记录2,字段1和记录1,字段3。 Please find a way to demonstrate what you're doing and the result you get — probably, add something to the question. 请找到一种方法来证明您在做什么和得到的结果—可能是在问题中添加了一些内容。 We can clean it up later when we've worked out what's going wrong with your setup. 当我们弄清您的设置出了什么问题时,我们可以稍后进行清理。 Please identify your platform reasonably clearly, too. 也请合理清晰地标识您的平台。

You can always use 'cut' from bash like so 您总是可以像这样使用bash中的“剪切”

cut -d ":" -f "1,3" < asdf
Assignment1:Admin
Assignment2:Paul

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM