Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

[Q] How to insert the content of the file into the other file???

Status
Not open for further replies.

CyanBlue

Technical User
Mar 6, 2002
16
US
Hi, guys...

Good morning... :)

I need to insert the content of the file into the specific line of another file... What would be the best way to do it???

For example... I have two files
Code:
--- FileA.txt   --- FileB.txt   --- FileA.txt
1               A               1
2               B               2
3               C               3
4               D               4
5               E               A
6               F               B
7                               C
8                               D
9                               E
                                F
                                5
                                6
                                7
                                8
                                9
---
As you can see, I have two files, FileA.txt and FileB.txt...
After a certain process, I want to insert all the lines of FileB.txt into the location of the line 5 of FileA.txt...
What do you think is the best way to do it???
Any help would be appreciated...
Have a nice day!!!

TIA
Jason
 
The simplest would be

# start
# insert 2nd file between rows 4 & 5 of first
ex FileA.txt <<END
4
r !cat FileB.txt
w
q
END
# end

with sed you could do

#! /bin/sh
# insert between rows 4 and 5
if [ $# -ne 2 ]; then
echo &quot;Usage: `basename $0` update-file input-file&quot; 1>&2
exit 1
fi

Tmp=&quot;${TMPDIR:=/tmp}/$$.`basename $0`&quot;
trap 'rm -f &quot;$Tmp&quot; > /dev/null 2>&1' 0
trap &quot;exit 2&quot; 1 2 3 13 15

FILEA=&quot;$1&quot;
FILEB=&quot;$2&quot;
LINE=5
CUTLN=$((5-1))
(
sed &quot;1,${CUTLN}!d;${CUTLN}q&quot; &quot;$FILEA&quot;
cat &quot;$FILEB&quot;
sed &quot;${LINE},\$!d&quot; &quot;$FILEA&quot;
) > $Tmp
mv -- &quot;${Tmp}&quot; &quot;$FILEA&quot;
# END OF SCRIPT

that one was cumbersome but useful in many cases. You should consider that kind of overhead when directing streams to a file and overwrite one of the sources. Let's see what the awk gurus come up with.

Cheers,
ND
 
Hi CyanBlue,

if you want to insert the content of a second file in your file you can use getline:

{
if (NR == line) {
print
while ((getline < &quot;FileB.txt&quot;) > 0) {
print
}
}
else print
}

awk -f script.awk -v line=4 FileA.txt

Greetz,
Sancho
 
Thank you guys...

Frankly, the code you guys provided are a bit hard to understand for a beginner like me, but I think I know how that code works...

Thanks again, and have a nice day!!!

Jason
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top