删除空字符(Shell脚本)

时间:2015-01-16 16:56:41

标签: linux bash shell unix sed

我到处都看,我运气不好。

我正在尝试计算当前目录和所有子目录中的文件,这样当我运行shell脚本count_files.sh时,它将产生类似的输出: $

2 sh
4 html
1 css
2 noexts

编辑以上输出应该在换行符上有每个计数和扩展名)

$ 其中noexts是没有任何句点作为扩展名的文件(例如:fileName)或具有句点但没有扩展名的文件(例如:fileName。)。

这条管道:

find * | awf -F . '{print $NF}'

为我提供了所有文件的完整列表,并且我已经找到了如何使用sed '/\//d'

删除没有任何句点的文件(例如:fileName)

我的问题是我无法从上面管道的输出中删除文件,这些文件由句点分隔但在句点之后具有NULL(例如:fileName。),因为它被分隔符“。”分隔。 p>

如何使用上面的sed从管道输入中删除空字符?

我知道这可能是一个快速修复,但我一直在谷歌搜索疯子没有运气。提前谢谢。

芯片

1 个答案:

答案 0 :(得分:1)

要过滤以.结尾的文件名,因为文件名是find输出中的整个输入行,您可以使用

sed '/\.$/d'

\.匹配文字点,$匹配行尾。

但是,我认为我会用awk完成所有事情。由于排序似乎没有必要:

编辑:使用awk和find -printf动作找到了更好的方法。

find . -type f -printf '%f\n' | awk -F. '!/\./ || $NF == "" { ++count["noext"]; next } { ++count[$NF] } END { for(k in count) { print k " " count[k] } }'

这里我们通过-printf '%f\n'来查找只打印文件名而没有前面的目录,这样可以更方便地为我们的目的使用 - 这样就不用担心了关于目录名称中的句点(例如/etc/somethingorother.d)。字段分隔符是'。',awk代码是

!/\./ || $NF == "" {        # if the line (the filename) does not contain
                            # a period or there's nothing after the last .
  ++count["noext"]          # increment the "noext" counter
                            # note that this will be collated with files that
                            # have ".noext" as filename extension. see below.
  next                      # go to the next line
}
{                           # in all other lines
  ++count[$NF]              # increment the counter for the file extension
}
END {                       # in the very end:
  for(k in count) {         # print the counters.
    print count[k] " " k
  }
}

请注意,这样一来,如果有一个文件" foo.noext",它将被计入没有文件扩展名的文件中。如果这是一个担心,请为没有扩展名的文件使用特殊计数器 - 除了数组或使用不能是文件扩展名的键(例如包含.或空字符串的键)。