提问者:小点点

随机选择文件并将其添加到另一个文件夹中的数据中


我有两个文件夹(DATA1和DATA2),里面有3个子文件夹(folder1、folder2和folder3),如下所示:

DATA1
    folder1/*.txt   contain 5 files
    folder2/*.txt   contain 4 files
    folder3/*.txt   contain 10 files

DATA2
    folder1/*.txt   contain 8 files
    folder2/*.txt   contain 9 files
    folder3/*.txt   contain 10 files

如上所述,每个子文件夹中有不同数量的文件,具有不同的名称,每个文件包含两列数据,如下所示:

1 -2.4654174805e+01
2 -2.3655626297e+01
3 -2.2654634476e+01
4 -2.1654865265e+01
5 -2.0653873444e+01
6 -1.9654104233e+01
7 -1.8654333115e+01
8 -1.7653341293e+01
9 -1.6654792786e+01
10 -1.5655022621e+01

我只想通过随机选择文件的第二列来添加数据文件夹,我的意思是来自DATA2/folder1/*. txt的任何随机数据(只有第二列)将被添加到DATA1/folder1/*.txt(只有第二列),类似地DATA2/folder2/*.txt将被添加到DATA1/folder2/*.txt等等。

最重要的是,我不需要打扰任何文件夹的第一列值,只需要对第二列进行操作。最后我想保存数据。

有人能提出同样的解决方案吗?我的目录和数据结构附在这里https://i.fluffy.cc/2RPrcMxVQ0RXsSW1lzf6vfQ30jgJD8qp.html

我想添加文件夹数据(从DATA2到DATA1)。首先进入DATA2/folder1并随机选择任何文件并选择其(文件)第二列(因为它由两列组成)。然后将选定的第二列添加到DATA1/folder1中存在的任何文件的第二列并将其保存到OUTPUT文件夹


共1个答案

匿名用户

因为没有代码可以开始,所以这不是一个现成的答案,而是一些可能会派上用场的构建块。

我将展示如何查找所有文件,选择一个随机文件,选择一个随机列并从该列中提取值。复制和调整此选项以选择随机文件和列以添加值,这留给读者作为练习。

#!/bin/bash

IFS=

# a function to generate a random number
prng() {
    # You could use $RANDOM instead but it gives a narrower range.
    echo $(( $(od -An -N4 -t u4 < /dev/urandom) % $1 ))
}

# Find files
readarray -t files < <(find DATA2/folder* -mindepth 1 -maxdepth 1 -name '*.txt')

# Debug print-out of the files array
declare -p files

echo Found ${#files[@]} files

# List files one-by-one
for file in "${files[@]}"
do
    echo "$file"
done

# Select a random file
fileno=$(prng ${#files[@]})
echo "Selecting file number $fileno"

filename=${files[$fileno]}
echo "which is $filename"

lines=$(wc -l < "$filename")
echo "and it has $lines lines"

# Add 1 since awk numbers its lines from 1 and up
rndline=$(( $(prng $lines) + 1 ))
echo "selecting value in column 2 on line $rndline"

value=$(awk -v rndline=$rndline '{ if(NR==rndline) print $2 }' "$filename")
echo "which is $value"

# now pick a random file and line in the other folder using the same technique