Bash脚本从命令行读取文件列表

时间:2014-09-12 20:14:41

标签: bash shell

我需要编写一个bash脚本,它将从命令行中获取输入(文件),其中包含一个文件列表。然后我需要在文件中打开这些文件并逐字读取,并保留列表中所有文件中每个单词出现次数。到目前为止,它打印出文件中的文件列表,还打印出文件本身。这就是我到目前为止所拥有的。我是bash脚本的新手,所以我不知道如何做到这一点。我感谢任何帮助。感谢

    #!/bin/bash

    wordArray=()
    countArray=()
    INPUT="$1";

    if [ -f "$INPUT" ]
    then
       find $name -type f
       echo "$name";
    else
       echo "$INPUT is not a file!";
    fi 

3 个答案:

答案 0 :(得分:2)

要计算一个文件中列表中所有文件中所有单词的出现次数,您可以使用:

xargs grep -hoP '\b\w+\b' < file_with_list | sort | uniq -c

示例:

file list.txt

test1.txt
test2.txt

test1.txt的

hello world

的test2.txt

hello word hello again

运行:

xargs grep -hoP '\b\w+\b' < list.txt | sort | uniq -c

打印

   1 again
   3 hello
   2 word

注意事项:

  • list.txt中的文件名不能包含空格......

答案 1 :(得分:0)

尝试:

#!/bin/bash

err() { echo "$@" >&2; return 1; }

printwords() {
    echo "Wordcounts in the: $@"
    for i in "${!words[@]}"
    do
        echo "$i => ${words[$i]}"
    done
}

input="$1"
[[ -n $input ]] || err "Usage: $0 filename" || exit 1
[[ -f $input ]] || err "File $input doesn't exists" || exit 2

declare -A words
while read -r file
do
    while read -r word
    do
        let words[$word]++
    done < <(grep -oP '\b\w+\b' "$file")
done < "$input"

printwords "$(cat "$input" | xargs)"

答案 2 :(得分:-1)

我认为你正在寻找类似这样的东西,而不是寻找。

for name in $INPUT; do echo $name; done

这将打印$ INPUT文件中的所有文件,当然你可以在该循环中执行任何其他操作。

相关问题