Keep the last instance of the record

Hi All,

I have a input file like

1| abc
1| abcd
1| abcde
2| abc
2| abcd
3| abcde

I want the output like

1| abcde
2| abcde

Any help would be highly appreciated.

Thanks in advance.

nawk ' /abcde/{i++;print i"|"$2} ' FS="|" infile

Hi,

It is not always 'abcde' in the last instance of a record.So, I would like to catch the last instance of a record for that key column where 1 and 2 are key's.

Thanks in advance.

Is the input sorted by key? That is, is the following input data valid or not?

1| abc
1| abcd
2| abc
2|abcd
1|abcdef
2|abcdef

Try this:

awk -F"|" 'k && $1 != k {print s}{k=$1;s=$1 FS $2}END{print s}' file
$ awk -F '|' '{A[$1]=$2}END{for (i in A) print i"|"A}' infile
1| abcde
2| abcd
3| abcde

This is using your example infile. If the last record would be 2 |abcde then the output is:

1| abcde
2| abcde

The input does not need to be sorted.

Hi Scrutinizer,

Thanks for your reply.

I am getting the following error with your code

awk: 0602-500 Quitting The source line is 1.

Thanks in advance.

---------- Post updated at 05:31 PM ---------- Previous update was at 05:23 PM ----------

Hi Franklin,

This code is working but has an issue.

One of my record is like below.

1|andndnnd
1| ahhhhhhhh MN
1| bbbbbbbbbb mmmmmmm MN101
1| bbbbbbbbbb mmmmmmm MN101  and some text here

the output was

1| bbbbbbbbbb mmmmmmm MN101 

instead of

1| bbbbbbbbbb mmmmmmm MN101  and some text here

Thanks in advance.

I don't understand. It works perfectly fine here. Did you copy paste the solution?

awk -F'|' '{a[$1]=$0}END{for(i in a)print a}' file

Hi All,

All the solutions are working fine but have a small issue with the data.

Some special characters are there within my data.

1| bbbbbbbbbb mmmmmmm MN101 --special characters -- and some text here

so the output was

1| bbbbbbbbbb mmmmmmm MN101

But i want the output like below

1| bbbbbbbbbb mmmmmmm MN101 --special characters -- and some text here

Any suggestions would be highly appreciated.

Thanks in advance.