使用两个变量形成单个文本文件

使用两个变量形成单个文本文件

我正在尝试创建一个包含以下内容的文本文件

user name is ${name}
and his mobile number is ${number}

我有 10 个用户和 10 个手机号码。用户名保存在 中user.txt,联系电话保存在 中contact.txt

user.txt如下所示。

apple
cat
tom

contact.txt如下所示,

1234
3456
5678

我的输出应该如下所示。

user name is apple
and his mobile number is 1234

user name is cat
and his mobile number is 3456

user name is tom
and his mobile number is 5678

我想要这个输出在单个文件中。有人可以帮我处理 shell 和 python 脚本吗?

答案1

这可以通过标准 shell 内置函数和常用工具来完成。

paste -d'|' user.txt contact.txt | while IFS='|' read user contact ; do
  printf "user name is %s\nand their mobile is %s\n" "${user}" "${contact}"
done

带有 bashism 的轻微混音,通常是输入重定向的首选。

while IFS='|' read user contact ; do
  printf "user name is %s\nand their mobile is %s\n" "${user}" "${contact}"
done < <(paste -d"|" user.txt contact.txt)

> "somefilename.txt"通过添加到任一命令的最后一行,可以将整个输出重定向到您选择的文件。

答案2

paste命令可用于将两个文件的行配对,以便我们可以更轻松地阅读它们:

paste user.txt contact.txt

这将创建一个由两个字段组成的制表符分隔的数据流。

这很容易阅读和修改,例如awk

awk -F '\t' '{ printf "user name is %s\nand his mobile number is %s\n\n", $1, $2 }'

这用于printf创建awk输出的字符串。从 的输出中读取的两个字段paste会自动读入$1和 ,$2并将它们插入到输出字符串中所示的位置%s(作为 的参数给出的下一个字符串的占位符printf)。-F '\t'命令行上的将awk字段分隔符设置为制表符。

将这两个放在一起并进行测试:

$ paste user.txt contact.txt | awk -F '\t' '{ printf "user name is %s\nand his mobile number is %s\n\n", $1, $2 }'
user name is apple
and his mobile number is 1234

user name is cat
and his mobile number is 3456

user name is tom
and his mobile number is 5678

>somename在命令末尾使用将其重定向到文件中。


另一种方法是修改输出字段分隔符 ( OFS) 和输出记录分隔符 ( ORS),而不是printf仅修改第一个和第二个字段(1末尾的尾随导致修改行的输出):

paste user.txt contact.txt |
awk -F '\t' -v OFS='\n' -v ORS='\n\n' '{ $1 = "user name is " $1; $2 = "and his mobile number is " $2 }; 1'

答案3

bash具有mapfile内置命令,该命令将文件作为每行一个元素读入数组。-t删除尾随换行符。然后您可以循环遍历数组:

#!/bin/bash
mapfile -t user <user.txt
mapfile -t number <contact.txt
for (( i=0 ; i<${#user[@]} ; i++ )) ; do
  echo "user name is ${user[i]}"
  echo "and his mobile number is ${number[i]}"
  echo
done

答案4

zsh

users=( ${(f)"$(<users.txt)"} )
numbers=( ${(f)"$(<numbers.txt)"} )
printf 'user name is %s\nand their mobile is %s\n\n' ${users:^numbers}

${A:^B}${A:^^B}是两个数组压缩运算符。当两个数组的长度不同时,可以看出两者之间的差异,例如在A=(a b c) B=(1 2 3 4 5)这种情况下${A:^B}产生a 1 b 2 c 3(丢弃 中的多余部分B),而${A:^^B}产生a 1 b 2 c 3 a 4 b 5(重用A成员来匹配 中的多余部分)B

相关内容