5

new to awk and try to do something that's probably simple but it's taking me a while. To simplify things, I have a text file called 'sample' and it contains the following line:

164516454242451BX%Apt 110 225 1784 Ohio USA

I want to get the following output using awk:

Apt 110 225

Is there a way I can split $1 so that "Apt" is a separate field? The code I'm trying is the below. I recieve no error, but the output is just 2 blank lines.

awk ' BEGIN { split($1," ","%") } print $2,$3,$4 END { print "" } ' sample 

1 Answer 1

13

You can % as one of the delimiters:

awk -F'[ %]' '{print $2, $3, $4}' file 

The same can be done using split as well:

awk '{split($1,a,/%/); print a[2], $2, $3}' file 
Sign up to request clarification or add additional context in comments.

3 Comments

+1. The 3rd arg for split() is a field separator which is a regexp with additional properties, not a string. The regexp delimiter is /, not " which is the string delimiter. Awk can construct regexps from strings by analyzing the context in which a string is used to see if it is a regexp context but it's best to keep your code clear and simple and use regexp delimiters for regexps unless you have a specific reason not to: split($1,a,/%/).
@EdMorton I am aware the 3rd arg is regex but didn't know it doesn't have to be a string. Edited as you suggested. Thanks for the information!
Unce upon a time in old, broken awk it had to be a string but all modern awks support RE delimiters. The difference between using a string and an RE is that with a string you have to double-escape any RE metachars that you want taken literally since awk uses up one of the escapes when it converts the string to an RE. The time to use string delimiters is when you want to construct an RE from a string plus a variable (split($0,a,somevar"etc")) or I sometimes use them for slightly improved readability when the RE is a forward-slash (split($0,a,"/") vs split($0,a,/\//)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.