1

I want to use the sed command (or something that works) to replace a word in a template file with a word in a line of another file.

As an example I have a file with a list of words, each word is in a different line and I want to use sed to take the first word (which is in the first line) and put it in another file where the word "value1" is written. I thought that with this post I could be able to do it, but I can't figure it out.

Graphic example:

File A:

Maria
Albert
Toni
Henry
Tom

File B:

The name of the student is: value1

Expected output for line 3:

The name of the student is: Toni

I want to be able to move one of the names from file A to file B where value1 is placed. And I want to do it multiple times.

Philippos
  • 13,453

1 Answers1

1

I'd use perl:

perl -ne '
  BEGIN{
    local $/ = undef;
    $template = <STDIN>; # slurp file B in
  }
  chomp;
  print $template =~ s/\bvalue1\b/$_/gr' fileA < fileB

If your version of perl is too old to support the r substitute flag, you can use a temporary variable:

perl -ne '
  BEGIN{
    local $/ = undef;
    $template = <STDIN>; # slurp file B in
  }
  chomp;
  ($out = $template) =~ s/\bvalue1\b/$_/g;
  print $out' fileA < fileB