[英]Copying content of 2 files in a new file by pairing the values in linux
There are supposed to be 2 files. 应该有2个文件。 One file has list of users and the other files has list of passwords.
一个文件包含用户列表,其他文件包含密码列表。 User file has 5 users and password file also has 5 passwords.
用户文件有5个用户,密码文件也有5个密码。 What I have to do here is create a new file and pair each user with all the available passwords in password file.
我在这里要做的是创建一个新文件,并将每个用户与密码文件中所有可用的密码配对。 For example: user 1 is to be paired with password 1, 2,3,4,5.
例如:用户1与密码1、2、3、4、5配对。 user 2 is to be paired with password 1,2,3,4,5 and so on.
用户2将与密码1,2,3,4,5配对,依此类推。
My question is: 1. What loop should be used here? 我的问题是:1.这里应该使用哪个循环? 2. My head says for pairing we need to use nested for loop.
2.我的头说要配对,我们需要使用嵌套的for循环。 is it correct?
这是正确的吗? 3. I can somehow imagine the 1st part of copying the contents but I'm not able to picture how to pair them.
3.我可以以某种方式想象复制内容的第一部分,但是我无法想象如何将它们配对。 So I need help and suggestions.
所以我需要帮助和建议。
EDIT: 编辑:
Sample input are the 2 files named Username and Password. 输入的示例是2个名为“用户名”和“密码”的文件。
Username file: 用户名文件:
User1 用户1
User2 用户2
.. ..
User5 用户5
Password file: 密码文件:
Pass1 合格1
Pass2 通行证2
.. ..
Pass5 合格5
Expected output is: 预期输出为:
User1-Pass1 User1-Pass1
User1-Pass2 User1-Pass2
.. ..
User1-Pass5 User1-Pass5
User2-Pass1 User2-Pass1
User2-Pass2 User2-Pass2
.. ..
User2-Pass5 User2-Pass5
and so on till we reach User5-Pass5 依此类推,直到我们到达User5-Pass5
Thanks. 谢谢。
Ad 1., 2. Yes, nested loop required. 广告1.,2。是,需要嵌套循环。
Let's expect one user per line and one password per line, then code would be: 假设每行一个用户和每行一个密码,那么代码将是:
> 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
If you write input sample and expected output, I can write something more specific. 如果您编写输入样本和预期输出,则可以编写更具体的内容。
always there is a better way 总是有更好的方法
$ join -t, -j 99 users pwords | cut -d, -f2-
for example 例如
$ 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
for -
delimiter change to join -t- -j 99 users pwords | cut -d- -f2-
对
-
定界符改变join -t- -j 99 users pwords | cut -d- -f2-
join -t- -j 99 users pwords | cut -d- -f2-
This is using a fictional column (99th) to create a join between each rows, which is called cross-product. 这是使用虚构的列(第99个)在每行之间创建联接,这称为叉积。 Since the key is missing in the first position of the output we need to cut it out at the end.
由于密钥在输出的第一个位置丢失,因此我们需要在末尾将其切除。
Do either of these help: 请执行以下任一帮助:
grep -Fwf file1 file2 or
awk 'NR==FNR{A[$1];next}$1 in A' file1 file2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.