提取一行,如果它包含指定列中的单词
问题描述:
我想提取一行,如果它包含文本文件的指定列中的单词。 我该如何在单线unix命令上做到这一点?也许与cat
,echo
,cut
,grep
与几个piples或东西。提取一行,如果它包含指定列中的单词
我有这种格式
#SentenceID<tab>Sentence1<tab>Sentence2<tab>Other_unknown_number_of_columns<tab> ...
文本文件的一个例子看上去文本文件看起来是这样的:
021348 this is the english sentence with coach . c'est la phrase française avec l'entraîneur . And then there are several nonsense columns like these .
923458 this is a another english sentence without the word . c'est une phrase d'une autre anglais sans le bus mot . whatever foo bar nonsense columns 2134234 $%^&
命令应输出,如果我要找的字是coach
在第二列:
021348 this is the english sentence with coach . c'est la phrase française avec l'entraîneur . And then there are several nonsense columns like these .
我可以用python做到这一点,但我正在寻找一个unix命令或一行代码:
outfile = open('out.txt')
for line in open('in.txt'):
if "coach" in line.split():
print>>outfile, line
答
这是怎么回事?
awk -F'\t' '{if($2 ~ "coach") print} your_file
-
-F'\t'
- >使得分隔符是标签。 -
$2 ~ "coach"
- >在第二个字段中寻找“coach”。 -
print $0
或print
- >打印整行。
编辑
sudo_O已经提出了以下,其中更短:
awk -F'\t' '$2~/coach/' file
答
对于这种需求,我总是用AWK:
awk的-F '\ t''$ 2〜/ coach/{print $ 0;}'< textFile
您可以使用$ x访问所有列,$ 0包含整个行。这个测试是用regexp进行的,在这种情况下非常简单,所以如果你的需求变得更复杂,这真的很有用。
+1但注意awks默认块是'{print}'所以你需要的只是'awk -F'\ t''$ 2〜/ coach /'文件' – 2013-03-26 10:50:58
很高兴认识到,@sudo_O!我用你的建议更新我的答案。谢谢! – fedorqui 2013-03-26 10:54:59