在 Linux 中仅获取文件名(不包括路径名)和记录计数



我有这个 linux 命令可以执行我需要它执行的操作(获取计数和文件名)。唯一的问题是它输出整个目录路径(123 dir1/dir2/sample1.txt)如何修改以仅包含文件名和计数(123 sample1.txt)?

find . -type f -name "*" -exec wc -l {} ;

获取: 123 目录1/目录2/样本1.txt

想要: 123 样本1.txt

您可以利用basename并使用管道:

find . -type f -name "*" -exec wc -l {} ; | xargs -n1 basename

试试sed!

find . -type f -name "*.xml" -exec wc -l {} ; | sed 's/./.*///g'

我的输出一开始有. 但如果你的不,则使用

find . -type f -name "*.xml" -exec wc -l {} ; | sed 's//.*///g'

编辑:sed 基本上用空字符串替换任何出现的./some/path/,或者如果使用第二个示例,它会替换/some/path/的出现。

EDIT2:这是第三个示例,无论输出是否在路径前面有 . 或没有.

find / -type f -name "*.xml" -exec wc -l {} ; | sed 's/.*/.*///g' 

如果您有路径名,则可以使用 basename 提取文件名,或者在 Bash 中,表达式${##*/} 。 在您的情况下,一种方法是先将路径名提取到变量中,然后调用basename或对变量使用表达式。

下面是一个示例。 它可能比需要的更复杂,但它应该说明这一点(我相信其他人可以指出更简单的方法):

#!/bin/bash
the_results=$( find . -type f -name "*" -exec wc -l {} ; )
echo "$the_results"
#
# Run 'find' command, iterating on each line of the result.
#
# We need to set IFS to not have a space, so the two returned items are
# treated as one result.
#
# We then parse each returned item into its two fields:
#    word count (a sequence of digits),
#    a space
#    path name (anything to end of line),
#
# The built-in BASH regular expression facility is used (the "=~"
# operator).  Substrings matched by parenthesized subexpressions
# within the regular expression are saved in the array variable
# BASH_REMATCH.
#
#
IFS=$'nb'
for a_result in $( find . -type f -name "*" -exec wc -l {} ; );
    do
        echo "result: $a_result"
        if [[ $a_result =~ ([0-9]+) (.*)$ ]]; then
            echo "${BASH_REMATCH[0]}"
            echo "    ${BASH_REMATCH[1]}"
            echo "    ${BASH_REMATCH[2]}"
            word_count="${BASH_REMATCH[1]}"
            path_name="${BASH_REMATCH[2]}"
            file_name="${path_name##*/}"
            echo "word_count: $word_count"
            echo "path_name: $path_name"
            echo "file_name: $file_name"
        else
            echo "Parse failed"
        fi
    done
unset IFS

最新更新