-1

Before:

file1

123
456

file2

foo
testing

After:

file1

123
456

file2

foo
testing 123

Any help would be greatly appreciated.

0

Try this,

sed -i "$ s/$/ $(head -1 file1)/" file2
testing 123
  • $ edit the last line of the file.
  • s/$ Substitute the EOL with $(head -1 file1), which is the first line of the file1.
  • This works for the given example, but will fail if the first line if file2 contains characters like single quote, slash or backslash – Philippos Jul 15 at 13:00
0

According to the content you gave in the example Here's what I suggest to you

echo -en " `head -1 file1`" >> file2
  • it would append after the last line of the file2 instead of appending to the last line... – msp9011 Jul 15 at 5:22
0

The task is less obvious than is looks at the first sight.

Either you use the Code by Slyx and remove the unwanted newline with sed $!N;$s/\n//;P;D afterwards or you find a string which is known not to be part of both files, let's say =snip= and do

sed '1h;1,/=snip=/d;$G;s/\n/ /' file1 <( echo =snip=) file2

The output can be piped to another file, then copied to file2 (even if your sed flavour has option -i this won't work when using parts of two files).

What does the code do?

  • 1h stores line 1 in the hold space (the "clipboard" of sed) to append it later
  • 1,/=snip=/d deletes everything from line 1 to our marker line, so only file2 will be printed
  • $G appends the saved line from the hold space for the last line ($)
  • s/\n/ / replaces an embedded newline by a whitespace. This will only happen in the last line after we appended the hold space
  • file1 <( echo =snip=) file2 are the files streamed to sed: first file1 to extract the first line, then a virtual file containing =snip= to know when file 1 ends, finally file2

Actually, a nice task to learn sed tricks.

0

There's ed:

ed file2 <<END
1a
$(head -n 1 file1)
.
1s/$/ /
1,2j
wq
END

But awk may be clearer:

awk -v "f1=$(head -n1 file1):" 'NR == 1 {$0 = $0 FS f1} 1' file2

That does not save file2 inplace. For that you can do, with GNU awk

gawk -i inplace -v "f1=$(head -n1 file1):" 'NR == 1 {$0 = $0 FS f1} 1' file2

or with any awk:

awk -v ... file2 > tmpfile2 && mv tmpfile2 file2

Another gawk option

gawk '
    FNR == 1 { if (NR == FNR) {f1 = $0; nextfile} else {$0 = $0 FS f1} }
    {print}
' file1 file2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.