Dheeban Chakkaravarthy
Dheeban Chakkaravarthy

Reputation: 249

how to replace a string with another string only on the last word of each line

I want to replace the 'UN' in the last word of each line with 'LK'.

Input file :

Y'UN 310R 07MAR DAUNEN UN2    
Y'UN 720R 07MAR DENSUN HK2    
Y'UN 721R 14MAR UNDDEN HK2    
Y'UN1692R 14MAR DEUNAY UN2

Output needed :

Y'UN 310R 07MAR DAUNEN LK2    
Y'UN 720R 07MAR DENSUN HK2    
Y'UN 721R 14MAR UNDDEN HK2    
Y'UN1692R 14MAR DEUNAY LK2

Upvotes: 2

Views: 322

Answers (2)

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

With awk:

awk '{sub(/UN/, "LK", $NF)}1' File

In the last field in each line ($NF), replace pattern UN (/UN/) with string LK ("LK"). Print the unaffected lines as well (1).

Output:

Y'UN 310R 07MAR DAUNEN LK2

Y'UN 720R 07MAR DENSUN HK2

Y'UN 721R 14MAR UNDDEN HK2

Y'UN1692R 14MAR DEUNAY LK2

Upvotes: 2

Vasfed
Vasfed

Reputation: 18464

The key here is using the 'end of line' anchor - $

sed -e 's/UN\([A-Z0-9]*\)$/LK\1/'

Upvotes: 1

Related Questions