Reputation: 3070
I searched for a good while but the closest I get to finding is appending to the last line.
One example I found was appending to the last line
sed '$ e cat word.txt' test.txt
The closest I got is using the x
command with sed
to get to the second to last line.
sed 'x;$ e cat word.txt' test.txt
However, I'd like to know how to append from the 3rd, 4th line, etc of the last line.
For example
word.txt
lorem ipsum...
test.txt
1
2
3
4
5
6
7
appending the word.txt
to the 4th to last line of test.txt
1
2
3
4
lorem ipsum...
5
6
7
The only examples I find are to append nth from the beginning of the line but not nth from the last last line.
Upvotes: 0
Views: 1583
Reputation: 26667
Using awk
, you can save all the lines and then print them in the END
block as
{ lines[NR] = $0 }
END{ for (i = 1; i <= NR; i++) {
if (NR-n + 1 == i)
print word;
print lines[i]
}
}
Example
$ awk -vn=3 -vword="$(cat word)" -f prog.awk file
1
2
3
4
lorem ipsum..
5
6
7
Upvotes: 0
Reputation: 33387
With awk you don't need to reverse the file prior to processing it:
awk -v last=3 -v toadd="$(<word.txt)" '
NR > last { print a[(NR-1) % last] }
{ a[(NR-1) % last] = $0 }
END{
print toadd
for(i=NR-last; i<NR; i++)
print a[i % last]
}' file
Upvotes: 0
Reputation: 37454
In GNU awk (ARGIND
variable):
$ awk -v nth=4 '
ARGIND==1 { s=s (s==""?"":ORS) $0; next }
ARGIND==2 { nr=NR; next }
ARGIND==3 && FNR==(nr-nth) { print s }
1' word test test
1
2
3
lorem ipsum...
4
5
6
7
It reads test
twice, calculates the record count on the first go.
Upvotes: 1
Reputation: 242083
Use head
and tail
:
{
head -n-3 text.txt
cat word.txt
tail -n3 text.txt
} > newfile.txt
Upvotes: 2