【问题标题】:copy all text from text file and insert it on the beginning of each line sed复制文本文件中的所有文本并将其插入每行的开头 sed
【发布时间】:2020-01-08 09:02:36
【问题描述】:

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

我尝试过使用 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

【问题讨论】:

  • paste 2.txt 3.txt > combined.txt 可能适合您。它将在不同内容之间的每一行上包含一个制表符字符。如果你真的需要它完全对齐,你可以在中间添加类似awk '{printf "%15s\t%s\n", $1, $2}' 的东西。祝你好运。

标签: file text sed add


【解决方案1】:

这可能对你有用(GNU sed):

sed -E 's/.*/printf "%-15s" &/e;s#(\S+).*#s/^\\<\1\\>/&\1/#' file1 | 
sed -f - -e 't;d' file2

这会从 file1 构建一个 sed 脚本并针对 file2 运行它。如果 file1 中的一行与 file2 的第一个单词匹配,则文件 1 中的 printf 格式化行将附加到 file2 中的匹配行,否则将被删除。如果您希望单独保留 file2 中不匹配的行,请从上述解决方案中删除 -e 't;d' 命令。

注意此解决方案不需要对任何一个文件进行排序,但是对于大文件可能会很耗时。

从你的 cmets 到 jas,如果文件是 1-1,这可能对你有用:

parallel -k 'printf "%-15s%s\n" {1} {2}' ::::+ file1 file2

【讨论】:

  • 谢谢,但是文件太大了。
  • @dani 如果文件是一对一的,请使用新的解决方案。
【解决方案2】:

为什么你需要第一个文件?为什么不只是:

$ awk '{print $1 "\t" $0}' 3.txt  | column -t -s $'\t'
u           u  = explanation here
ubbia       ubbia = explanation here
ubbidiente  ubbidiente = explanation here
ubbidienza  ubbidienza = explanation here
ubbidire    ubbidire = explanation here
ubertoso    ubertoso = explanation here

【讨论】:

  • 对不起,我的错。我在第一个文件中有 ubbia 第一个世界,然后在第二个文件中有 ùbbia = 解释。我不能只是复制它,它也会复制带重音的字母。感谢您的回答
【解决方案3】:

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

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

【讨论】:

  • @dani,对我来说效果很好,你能通过cat -v Input_file检查一下你是否有控制M字符吗?
  • 是的。我有M字符。使用 shellter 发布的粘贴 2.txt 3.txt > combined.txt 对我来说效果很好
  • @dani,请通过 tr -d '\r' &lt; Input_file &gt; temp &amp;&amp; mv temp Input_file 删除它们,然后尝试我的代码。
  • 我试过了。现在有效,但效果不佳。我在文本中找到了单词,但这些单词与输入文件中的其他单词不一致。
  • @dani,看我的帖子我得到了正确的输出,你是怎么得到它的?
猜你喜欢
  • 2011-05-04
  • 2013-08-15
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-20
  • 2017-12-07
相关资源
最近更新 更多