task at hand
you have two files :: file1.txt and file2.txt
you want to insert the contents of file1.txt into file2.txt starting at line number 2
contents of file1.txt before the process
because i m stupid
contents of file2.txt before the process
why do you want to do a phd ?
ok then, may god rest your spirit in peace.
contents of file2.txt after the process
why do you want to do a phd ?
because i m stupid
ok then, may god rest your spirit in peace.
this is how you do it
sed ‘2r file1.txt’ < file2.txt > tempFile.txt
mv tempFile.txt file2.txt
the r stands for the read FILENAME command and is a GNU extension i believe. so it may not be available on all platforms. to find out more try
info sed
and in particular see the section 3.6 Less Frequently-Used Commands
How would you achieve this inline?
hello and thanks for your question. i am sorry though i don’t really understand what you mean by ‘inline’. did you mean how one can achieve this without using a temporary file and then moving that temporary file to file2.txt? if you try the following
you will end up with an empty file2.txt at least in GNU bash, version 4.2.37. however you may use a utility called sponge provided by the moreutils package.
http://joeyh.name/code/moreutils/
You can do it this way inline:
sed -i ‘2r file1.txt’ file2.txt
thanks 🙂
what if u need to put the lines of one file before the last line of another file instead of starting from top..??
well the most obvious approach is to simply use what ever i have already talked about i.e.
sed -i ‘Nr b.txt’ a.txt
where N is the second last line number of a.txt. and how would you find that? simply examine the file or invoke the wc command from the coreutils package and figure out the number of lines the file has, like this:
wc -l <a.txt
also you can put everything together and come up with this scary thing
sed "$(($(wc -l < a.txt) – 1))r b.txt" a.txt
where N is replaced by
$(($(wc -l < a.txt) – 1))
# $(( )) thingy allows for arithmetic on variables
here i have used bash arithmetic to subtract 1 from the count given by wc.
thing to watch out for in this sed invocation is the use of double quotes that allow for bash arithmetic to work. i had used single quotes earlier.
but you see we really do not gain anything by doing this. probably a much better way is to use
cat <(head -n-1 a.txt) b.txt <(tail -1 a.txt) > c.txt
where we use cat to concatenate the 3 constituent parts of the final file
head -n-1 a.txt
<(tail -1 a.txt)
the “<()" thingy is an example of process substitution
[…] ingin menampilkan hasil penggabungan text satu file ke file lain namun kita ingin agar file dari file kedu… maka bisa menggunakan […]
Thank you! This just solved my issue.
thanks 🙂