【问题标题】:How to search same pattern .csv files in different directory and combine them into one csv file with single row of header in shell script如何在不同目录中搜索相同模式的 .csv 文件并将它们组合成一个 csv 文件,并在 shell 脚本中使用单行标题
【发布时间】:2020-06-06 19:43:23
【问题描述】:

我有相同的模式 .csv 文件:

  • relsendTest.csv
  • relsendTest2.csv
  • relsendTest3.csv

在文件夹中

  • neolog201
  • neolog202
  • neolog203

我当前的脚本可以将这些文件转换成一个单独的 csv 文件

head -1 relsendTest.csv > output.csv
for filename in $(ls relsend*.csv); do sed 1d $filename >> output.csv; done

但问题是这些文件位于同一目录中。我在不同的目录中有这种模式的文件。我需要将这些多个文件合并为一个。

【问题讨论】:

  • 使用find . -name "relsend*.csv" -print 构建文件列表。在列表上循环以构建您的单个 CSV 文件。
  • 我在我的 (ls relsend*.csv) 中替换了您的代码,但得到了相同的结果。我当前的目录有一些这些文件,它们被添加到列表中。但一些 csv 文件在其他文件夹中。这些文件没有加起来

标签: shell csv unix


【解决方案1】:

为了测试我的解决方案,我创建了这个结构:

Dir: neolog201
    relsendTest.csv
Dir: neolog202
    relsendTest2.csv
Dir: neolog203
    relsendTest3.csv

然后测试了find

$ find . -name "relsendTest*.csv" -print
./neolog203/relsendTest3.csv
./neolog202/relsendTest2.csv
./neolog201/relsendTest.csv

所以你现在有了文件列表。完整的脚本:

#!/bin/bash

# Get the list of files
fileslist=$(find . -name "relsendTest*.csv" -print)

# The header of the output.csv is the first line of the first file in the list
head -1 $(echo $fileslist | awk '{print $1}') > output.csv

# Then loop on each file and get all lines except the first line of each file
for F in $fileslist
do
    sed 1d $F >> output.csv
done

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    相关资源
    最近更新 更多