0

I have csv file as mentioned below format.

1,123-456,IND,91,UAE,97,USA,01,SA,27
3,345-678,AUS,61,SLA,94,NZW,64,RS,7

it should check based on ,(\w{3}),(\d{2}), pattern check and how many times its matching it should show in | delimited as mentioned below, using AWK command how to achieve.

expected output

1,123-456,IND,91|UAE,97|USA,01
3,345-678,AUS,61|SLA,94|NZW,64
8
  • 1
    Welcome to the site. Would you mind editing your post to indicate what you already tried? Otherwise contributors might suggest a solution that you already know won't work.
    – AdminBee
    Commented Oct 29, 2020 at 16:36
  • 3
    The second line should be 3,345-678,AUS,61|SLA,94|NZW,64, right? Commented Oct 29, 2020 at 16:41
  • Does it have to be awk? It is much easier in other tools. Also, why is the SA, 27 disappearing in your output?
    – terdon
    Commented Oct 29, 2020 at 16:44
  • @terdon, "SA" is only 2 chars, not 3 Commented Oct 29, 2020 at 16:46
  • 2
    Do you REALLY want an awk solution or are you going to ask for a different solution after getting the awk solution like in your previous question?
    – Ed Morton
    Commented Oct 29, 2020 at 17:17

1 Answer 1

2

When you say \w+, I assume you actually mean [a-zA-Z] since \w also matches numbers and underscores and it looks like you only want letters. In fact, based on your example, you might only want capital letters. Finally, and again I'm guessing here since you don't explain, it looks like you want to exclude cases where the letters string is not exactly 3 characters long. If so, here's a way of doing what you want in Perl:

$ perl -lne '/^(.*?),[A-Z]{3},\d{2},/; $start=$1; @k=(/,(\w{3},\d{2})/g); print "$start,", join("|",@k)' file
1,123-456,IND,91|UAE,97|USA,01
3,345-678,AUS,61|SLA,94|NZW,64

Alternatively, and assuming you only want to make the matches after the 2nd field, you can do this in awk:

$ awk -F, -v OFS="," '{
                        for(i=3;i<=NF;i+=2){
                        if ($i~/^[A-Z]{3}$/ && $(i+1)~/^[0-9]{2}$/){
                            k ? k=k"|"$i","$(i+1) : k=$i","$(i+1); 
                        }
                       } print $1,$2,k; k=""}' file
1,123-456,IND,91|UAE,97|USA,01
3,345-678,AUS,61|SLA,94|NZW,64

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .