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,237
  • 2
  • 37
  • 76

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
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • It gives me a compilation error and I never used perl... :/ Any suggestions? – Enrique Torelló Perelló Apr 18 '18 at 10:05
  • @EnriqueTorellóPerelló, possibly, you have an old version of `perl` before the `r` flag was added. – Stéphane Chazelas Apr 18 '18 at 10:15
  • where do I specify the line from file A to replace in file B? I suppose that value1 is the value from file B to be replaced. Right? – Enrique Torelló Perelló Apr 18 '18 at 10:41
  • @EnriqueTorellóPerelló, that answer answers your question as currently stated in the body of your question, the additional comments to your question seem to suggest a different question. I've given up trying to guess what you actually want to do. You should edit your question with a more relevant example. – Stéphane Chazelas Apr 18 '18 at 11:53