【问题标题】:Bash script to read a file from the command line with list of files用于从命令行读取文件列表的 Bash 脚本
【发布时间】:2014-11-07 02:19:18
【问题描述】:

我需要编写一个 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 

【问题讨论】:

  • 我不明白这怎么可能做到你所说的那样。你在哪里设置$name
  • 如果文件中有文件名,为什么需要find

标签: bash shell


【解决方案1】:

我认为您正在寻找类似的东西而不是 find。

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

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

【讨论】:

  • 请测试您的脚本 - 这将只打印变量 $INPUT 的内容,而不是文件的内容,名称存储在 INPUT...
  • 是的,这比使用 find 效果更好。谢谢你。但是如何打开该列表中的这些文件以将每个单词读入一个数组以计算每个单词的出现次数?
  • 做 cat $name 而不是做 echo $name
  • 啊,我明白了……是的,echo 只是打印文件本身的名称。谢谢
【解决方案2】:

试试:

#!/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)"

【讨论】:

  • 它无法识别 -A 并打印出来:grep: : No such file or directory
【解决方案3】:

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

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

例子:

文件列表.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 中的文件名不能包含空格...

【讨论】:

  • 那行得通。谢谢!如果我想按出现次数对其进行排序...我需要更改什么?
  • 另外,它只需要将有效单词打印到输出文件...我知道如何检查有效单词,但不在您编写的代码中。
猜你喜欢
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多