通过配对 linux 中的值将 2 个文件的内容复制到一个新文件中

Copying content of 2 files in a new file by pairing the values in linux

应该有 2 个文件。一个文件包含用户列表,另一个文件包含密码列表。 用户文件有5个用户,密码文件也有5个密码。我在这里要做的是创建一个新文件并将每个用户与密码文件中的所有可用密码配对。例如:用户 1 要与密码 1、2、3、4、5 配对。用户 2 将与密码 1,2,3,4,5 等配对。

我的问题是: 1、这里应该用什么循环? 2.我的头说我们需要使用嵌套的for循环进行配对。这是正确的吗? 3. 我能以某种方式想象复制内容的第一部分,但我无法想象如何将它们配对。所以我需要帮助和建议。

编辑:

示例输入是名为用户名和密码的 2 个文件。

用户名文件:

用户 1

用户 2

..

用户 5

密码文件:

通过1

通过2

..

通过5

预期输出为:

User1-Pass1

User1-Pass2

..

User1-Pass5

User2-Pass1

User2-Pass2

..

User2-Pass5

依此类推,直到我们到达 User5-Pass5

谢谢。

广告 1.、2.是,需要嵌套循环。

假设每行一个用户,每行一个密码,那么代码将是:

> concat  # delete file content
for usr in `cat file_with_users`
do  
    for pwd in `cat file_with_passwords`
    do
        echo "$usr-$pwd" >> result_file
    done 
done

如果你写输入样本和预期输出,我可以写得更具体一些。

做这些帮助之一:

grep -Fwf file1 file2 or 
awk 'NR==FNR{A[];next} in A' file1 file2

总有更好的办法

$ join -t, -j 99 users pwords | cut -d, -f2-

例如

$ echo u{1..5} | tr ' ' '\n' > users
$ echo p{1..5} | tr ' ' '\n' > pwords

$ join -t, -j 99 users pwords | cut -d, -f2-
u1,p1
u1,p2
u1,p3
u1,p4
u1,p5
u2,p1
u2,p2
...
u5,p4
u5,p5

- 分隔符更改为 join -t- -j 99 users pwords | cut -d- -f2-

这是使用一个虚构的列(第 99 列)在每行之间创建一个连接,这称为叉积。由于输出的第一个位置缺少密钥,我们需要在最后将其删除。