遍历AWK命令不起作用 [英] looping over AWK commands doesn't work

查看:320
本文介绍了遍历AWK命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含每行每一个字一个巨大的字典文件,想通过单词的第一个字符的文件分割。

I have a huge dictionary file that contains each word in each line, and would like to split the files by the first character of the words.

A.TXT - >只包含一个开始的话

a.txt --> only contains the words that start with a

我用这个命令AWK成功提取以b开头的单词。

I used this awk commands to successfully extract words that start with b.

  awk 'tolower($0)~/^b/{print}' titles-sorted.txt > b.txt

现在我想这个迭代所有字母

Now I wanted to iterate this for all alphabets

  for alphabet in {a..z} 
    do
        awk 'tolower($0)~/^alphabet/{print}' titles-sorted.txt > titles-links/^alphabet.txt
    done 

但结果文件不包含任何内容。我做错了什么?我甚至不知道如何调试这一点。谢谢!

But the result files contain no contents. What did I do wrong? I don't even know how to debug this. Thanks!

推荐答案

由于您的awk程序是单引号,也不会有任何shell变量扩展。在这个例子中:

Because your awk program is in single quotes, there will not be any shell variable expansion. In this example:

awk 'tolower($0)~/^alphabet/{print}' titles-sorted.txt > titles-links/^alphabet.txt

...你正在寻找与文字字符串开头的行字母

这将工作:

awk "tolower(\$0)~/^$alphabet/{print}" titles-sorted.txt > titles-links/$alphabet.txt

请注意几点:


  • 我们使用的是双引号,不抑制shell变量扩展。

  • 我们需要逃避 $ $ 1,0 ,否则外壳将展开。

  • 我们需要更换字母 $字母,因为这是你如何引用shell变量。

  • 我们需要更换 ^字母在传递给&GT的文件名 $字母 ;

  • We are using double quotes, which does not inhibit shell variable expansion.
  • We need to escape the $ in $0, otherwise the shell would expand that.
  • We need to replace alphabet with $alphabet, because that's how you refer to shell variables.
  • We need to replace ^alphabet with $alphabet in the filename passed to >.

您也可以改变shell变量变成一个awk变量与 -v ,并做到这一点:

You could also transform the shell variable into an awk variable with -v, and do this:

for alphabet in {a..z} ; do
    awk -valphabet=$alphabet 'tolower($0)~"^"alphabet {print}' /usr/share/dict/words > words-$alphabet.txt
done

这篇关于遍历AWK命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆