首页 > 解决方案 > 复制文本文件中的所有文本并将其插入每行的开头 sed

问题描述

我想复制一个文本文件中的所有文本,并在另一个文本文件中的每一行的开头添加。

我试过 sed,我可以在每行的开头放一个字符,但我不知道如何从另一个文件复制文本

我试过这个:

sed 's/^/#/' 2.txt > 3.txt

但这只会放置一个字符或字符串。

例子:

我在 2.txt 中有这样的话:

u
ubbia
ubbidiente
ubbidienza
ubbidire
ubertoso

在第二个 3.txt 我有相同的行但有解释:

u  = explanation here
ubbia = explanation here
ubbidiente = explanation here
ubbidienza = explanation here
ubbidire = explanation here
ubertoso = explanation here

我想要这个结果:

u              u  = explanation here
ubbia          ubbia = explanation here
ubbidiente     ubbidiente = explanation here
ubbidienza     ubbidienza = explanation here
ubbidire       ubbidire = explanation here
ubertoso       ubertoso = explanation here

标签: filetextsedadd

解决方案


您能否尝试以下操作,此解决方案将根据第一列的最大长度的长度在输出中进行缩进(已为其编写了逻辑),并使用给定的样本进行了测试。

awk '
FNR==NR{
  a[FNR]=$1
  c[$1]
  next
}
($1 in c){
  b[++count]=$0
  len=len>length($1)?len:length($1)
}
END{
  for(i=1;i<=count;i++){
    val=len<length(b[i])?len+(len-length(a[i])):len
    printf("%s%"val"s%s\n",a[i],OFS,b[i])
  }
}
'  2.txt 3.txt

输出如下。

u                   u  = explanation here
ubbia               ubbia = explanation here
ubbidiente          ubbidiente = explanation here
ubbidienza          ubbidienza = explanation here
ubbidire            ubbidire = explanation here
ubertoso            ubertoso = explanation here

推荐阅读