【问题标题】:sed contents of file appended to specific line in another filesed 文件的内容附加到另一个文件中的特定行
【发布时间】:2025-11-21 09:40:02
【问题描述】:

我有一个相当复杂的sed 脚本,它将文件的内容写入新文件中的单行逗号分隔列表。

我想读取该文件并将其写入另一个文件的特定行的末尾。真正更好的是读取原始文件,将逗号分隔的列表直接写入新文件中的指定行并跳过中间人。

sed -n '/# FirstMark/,/# EndMark/p' client_list.formal|grep -v "#"|awk -F\< '{print $2}'|awk -F\> '{print $1}'|xargs|sed -e 's/ /,\ /g'|sort -u|sed -i /writes all this stuff to end of specified line > file.txt

细分是:

  1. sed -n '/ # FirstMark/(从这个字符串开始阅读)

  2. ,/# EndMark/p'(在此字符串处停止阅读)

  3. client_list.formal(来自此文件)

  4. grep -v "#"(删除所有注释掉的行)

  5. awk -F\&lt; '{print$2}'|awk-F\&gt; '{print $1}'(打印 之间的所有内容)

  6. xargs|sed -e 's/ /,\ /g'|sort -u(全部放在同一行,添加逗号,并仅排序)

  7. 最后一位应将所有输出写入新文件中指定行的末尾。

我目前的工作只是将其写入文件。然后我 sed -i 该文件到另一个文件的每一行的末尾(该文件只有一行。但是会有其他文件有多行,每一行都有自己的列表,所有列表都将从一个构建源文件。)

到目前为止,我已经看到了如何将它插入到文件中的特定行中,将其附加到文件末尾,而不是附加到指定行的末尾。我是不是想多了?我觉得我想多了。

client_list.formal 示例

# Formal Client Name1
Contact Lastname,Firstname &lt;email@address.tld&gt;
Contact Lastname,Firstname &lt;email@address.tld&gt;
# Formal Client Name2
Contact Lastname,Firstname &lt;email@address.tld&gt;

示例文件写入:

email@address.tld、email@address.tld、email@address.tld、email@address.tld、email@address.tld

要插入的示例文件:

alias1: email@address.tld, email@address.tld, email@address.tld, email@address.tld
alias2:
alias3:email@address.tld, email@address.tld, email@address.tld, email@address.tld

操作完成时的预期文件格式:

alias1: email@address.tld, email@address.tld, email@address.tld, email@address.tld
alias2: email@address.tld, email@address.tld, email@address.tld, email@address.tld,
alias3: email@address.tld, email@address.tld, email@address.tld, email@address.tld

【问题讨论】:

  • 发布示例输入文件、要插入的文件和预期输出。
  • 老实说,我认为这里的菊花链 awk/sed 已经够复杂了。您是否有特殊原因避免使用perl
  • 主要是因为我不懂任何编程语言。我正在自学 bash 脚本。这周我拿起了 O'Reilly 的 Python 书籍。 :-)

标签: bash sed


【解决方案1】:

老实说 - 命令链足够大,我认为是时候打破像 perl 这样的编程语言了。

您尝试执行的任务可以像这样完成

#!/usr/bin/env perl

use strict;
use warnings;

#open your input file
open ( my $email_file, '<', 'client_list') or die $!;
#read all the lines with <email@somewhere>, and join them on a ','
my $address_list = join ( ",", map { m/<(.*)>/ } <$email_file> );
print "Inserting $address_list\n"; 
close ( $email_file ); 

#open filename     
open ( my $file2, '<', "insert_file_name" ) or die $!;
open ( my $results_file, '>', "output_file" ) or die $!;
#iterate file2.  
while ( my $line = <$file2> ) {
    # if condition matches, replace end of line with the address list above; 
    if ( $line =~ m/alias2/ ) { $line =~ s/$/$address_list/ };
    print {$results_file} $line;
}
close ( $file2 );
close ( $results_file );

【讨论】:

  • 我创建了测试用例文件来查看它的作用。我看到它是如何有用的。我需要了解更多关于pearl的信息,以便我可以调整它以提取email_file中的选定条目并将它们附加到results_file中的选定行。从命令行调用时,这肯定需要参数。