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

时间:2015-01-29 18:38:01

标签: linux

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

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

获取:123 dir1 / dir2 / sample1.txt

     

旺旺:123 sample1.txt

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

尝试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' 

答案 2 :(得分:0)

如果您有路径名,则可以使用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=$'\n\b'

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