gpt4 book ai didi

linux - 删除空字符(Shell 脚本)

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:15 26 4
gpt4 key购买 nike

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

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

2 sh
4 html
1 css
2 noexts

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

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

这条管道:

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

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

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

我的问题是我无法从上述管道的输出中删除由句点分隔但在句点后为 NULL 的文件(例如:文件名。),因为它由分隔符“.”分隔。

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

我知道这可能是一个快速解决方案,但我一直像疯子一样在谷歌上搜索,但没有运气。提前致谢。

芯片

最佳答案

要过滤以 . 结尾的文件名,因为文件名是 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' 来 find 让它只打印文件名而不打印前面的目录,这使得我们的目的更容易使用 - 这个这样就无需担心目录名称中的句点(例如 /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”,它会被算在没有文件扩展名的文件中。如果担心这一点,请为没有扩展名的文件使用一个特殊的计数器——要么与数组分开,要么使用不能是文件扩展名的键(例如包含 . 或空的文件扩展名)字符串)。

关于linux - 删除空字符(Shell 脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27988933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com