Tuesday 16 February 2016

Add a character at a specific location within strings using Awk

Folks, in previous examples we saw how to add a prefix to strings in a file and how to add a suffix to strings in a file. In today's example, we'll see how to add a character somewhere in the middle of multiple strings in a file at the same time.

We'll use the same data as used in previous examples. Let's use a text file named Phones_unformatted.txt with the following phone numbers data :

2127841212
3458922345
7713398403
6461228847

Now we want to add a - sign after the first 3 digits to separate the area code. Notice that all phone numbers are of 10 digits. We want to add a - sign between the 3rd and 4th character.

For doing this lets use awk again :

awk '$0=substr($0,1,3) "-" substr($0,4,7)' Phones_unformatted.txt

Output :

212-7841212
345-8922345
771-3398403
646-1228847


Notice how we have used substr() function to split the entire 10 digit phone number into 2 parts. The first part is between 1-3rd character and the second part is from 4-10th character.

Similarly, lets say for e.g. we want to add the - sign twice within the string i.e once between 3rd and 4th character and the next - between 6th and 7th character. The awk code for doing this is as follows :

awk '$0=substr($0,1,3) "-" substr($0,4,3) "-" substr($0,7,4)' Phones_unformatted.txt

Output :

212-784-1212
345-892-2345
771-339-8403
646-122-8847

This way, you could append the string with the "-" character or anything like a dot "." or maybe just a whitespace " ".

awk '$0=substr($0,1,3) " " substr($0,4,3) " " substr($0,7,4)' Phones_unformatted.txt

Output :

212 784 1212
345 892 2345
771 339 8403
646 122 8847

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker