unix shell脚本:合并2个不同文本文件的数据(行)

unix shell脚本:合并2个不同文本文件的数据(行)

文件有许多条目,但对于示例发布,每个文件只有 2 个条目。我想将文件1的第一行内容与文件2的第一行内容合并,依此类推。示例如下。

文件1.txt

Start Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
Start Date: 2019-01-08 04:16:57; End Date: 2019-01-08 04:17:02; Difference in seconds = 5

文件2.txt

Fnb_dm__exachange_rollback_character
dnb_exchange_brm_rollback_character

我想要如下输出:

Fnb_dm__exachange_rollback_character :Start Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
dnb_exchange_brm_rollback_character :Start Date: 2019-01-08 04:16:57; End Date: 2019-01-08 04:17:02; Difference in seconds = 5

如何使用 ksh 做到这一点?

答案1

您可以使用以下paste命令 - 例如,使用冒号分隔符逐行合并文件:

$ paste -d: file2.txt file1.txt
Fnb_dm__exachange_rollback_character:Start Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
dnb_exchange_brm_rollback_character:Start Date: 2019-01-08 04:16:57; End Date: 2019-01-08 04:17:02; Difference in seconds = 5

如果您需要多字符分隔符,则可以使用prex。

$ pr -TmJS' :' file2.txt file1.txt
Fnb_dm__exachange_rollback_character :Start Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
dnb_exchange_brm_rollback_character :Start Date: 2019-01-08 04:16:57; End Date: 2019-01-08 04:17:02; Difference in seconds = 5

答案2

我已经按照下面的方法完成了并且效果很好

i=`awk 'NR==1{print $0}' file1`;awk -v i="$i" 'NR==1{$0=$0i}1' file2

输出

Fnb_dm__exachange_rollback_characterStart Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
dnb_exchange_brm_rollback_character

答案3

我已经按照下面的方法完成了并且效果很好

for i in 1 2; do j=`sed -n ''$i'p' file1`;sed -n ''$i'p' file2|sed "s/.*/&$j/g"; done

输出

Fnb_dm__exachange_rollback_characterStart Date: 2019-01-08 04:14:59; End Date: 2019-01-08 04:15:50; Difference in seconds = 51
dnb_exchange_brm_rollback_characterStart Date: 2019-01-08 04:16:57; End Date: 2019-01-08 04:17:02; Difference in seconds = 5

相关内容