gpt4 book ai didi

linux - 在Linux中使用文件名和文件内容创建CSV文件

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:20 26 4
gpt4 key购买 nike

我有一个包含超过 400K txt 文件的文件夹。

名称如

deID.RESUL_12433287659.txt_234323456.txt
deID.RESUL_34534563649.txt_345353567.txt
deID.RESUL_44235345636.txt_537967875.txt
deID.RESUL_35234663456.txt_423452545.txt

每个文件都有不同的内容

我想获取文件名和文件内容并放入 CSV 中。

类似于:

file_name,file_content
deID.RESUL_12433287659.txt_234323456.txt,Content 1
deID.RESUL_34534563649.txt_345353567.txt,Content 2
deID.RESUL_44235345636.txt_537967875.txt,Content 3
deID.RESUL_35234663456.txt_423452545.txt,Content 4

我知道如何使用以下方法获取 CSV 目录中的所有文件:

find * > files.csv

我怎样才能获取文件的内容?

最佳答案

  1. find * 有点奇怪,find 已经递归扫描了。 find . 足以包含所有 find * (好吧,除非您考虑到一些奇怪的 shell glob 规则)。
  2. 我们需要迭代这些文件。另外,最好删除换行符。

# create file for a MCVE
while IFS=' ' read -r file content; do echo "$content" > "$file"; done <<EOF
deID.RESUL_12433287659.txt_234323456.txt Content 1
deID.RESUL_34534563649.txt_345353567.txt Content 2
deID.RESUL_44235345636.txt_537967875.txt Content 3
deID.RESUL_35234663456.txt_423452545.txt Content 4
EOF

{
# I'm using `|` as the separator for columns
# output header names
echo 'file_name|file_content';
# this is the hearth of the script
# find the files
# for each file execute `sh -c 'printf "%s|%s\n" "$1" "$(cat "$1")"' -- <filename>`
# printf - nice printing
# "$(cat "$1")" - gets file content and also removes trailing empty newlines. Neat.
find . -type f -name 'deID.*' -exec sh -c 'printf "%s|%s\n" "$1" "$(cat "$1")"' -- {} \;
} |
# nice formatting:
column -t -s'|' -o ' '

将输出:

file_name                                       file_content
./deID.RESUL_44235345636.txt_537967875.txt Content 3
./deID.RESUL_35234663456.txt_423452545.txt Content 4
./deID.RESUL_34534563649.txt_345353567.txt Content 2
./deID.RESUL_12433287659.txt_234323456.txt Content 1

关于linux - 在Linux中使用文件名和文件内容创建CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com