linux 将每一行csv导入bash命令[复制]

ny6fqffe  于 2023-01-29  发布在  Linux
关注(0)|答案(3)|浏览(111)
    • 此问题在此处已有答案**:

Count all occurrences of a string in lots of files with grep(16个答案)
3天前关闭。
这篇文章是编辑和提交审查3天前。
我有一个没有标题的单列CSV文件,我想迭代地找到每一行的值,并计算它在几个文件中出现的次数。
大概是这样的

for i in file.csv:
 zcat *json.gz | grep i | wc -l

但是,我不知道如何迭代csv并向前传递值
假设file.csv为:

foo,
bar

如果foo*json.gz中出现了20次,bar*json.gz中出现了30次,我希望命令的输出为:

20
30
    • 以下是我找到的解决方案:**
while IFS=',' read -r column; do
  count=$(zgrep -o "$column" *json.gz | wc -l)
  echo "$column,$count"; done < file.csv
cclgggtu

cclgggtu1#

您可以通过一个grep操作将file.csv视为一个 patterns 文件(每行获取一个模式)来实现这一点:

grep -f file.csv -oh *.json | wc -l
  • -o-仅打印匹配的部件
  • -h-禁止输出文件名
wlwcrazw

wlwcrazw2#

您可以迭代cat run through子进程的输出:

for i in `cat file.csv`: # iterates through all the rows in file.csv
   do echo "My value is $i"; done;
q3qa4bjr

q3qa4bjr3#

使用chatgpt:),请尝试以下操作:

#!/bin/bash

# Define the name of the CSV file
csv_file="path/to/file.csv"

# Extract the values from each row of the CSV file
values=$(cut -f1 "$csv_file" | uniq -c)

# Loop through each file
for file in path/to/file1 path/to/file2 path/to/file3
do
    # Extract the values from each row of the file
    file_values=$(cut -f1 "$file" | uniq -c)

    # Compare the values and print the results
    for value in $values
    do
        count=$(echo $value | cut -f1 -d' ')
        val=$(echo $value | cut -f2 -d' ')
        file_count=$(echo $file_values | grep -o "$val" | wc -l)
        echo "$val appears $count times in $csv_file and $file_count times in $file"
    done
done

相关问题