How to convert the following text to comma seperated list using awk - Need to skip headers and trailers

StackOverflow https://stackoverflow.com/questions/23617528

  •  21-07-2023
  •  | 
  •  

Question

+---------------------------------+------------+------+----------+
| Name | NumCourses | Year | Semester |
+---------------------------------+------------+------+----------+
| ABDULHADI, ASHRAF M | 2 | 1990 | 3 |
| ACHANTA, BALA | 2 | 1995 | 3 |
| ACHANTA, BALA | 2 | 1996 | 3 |
+---------------------------------+------------+------+----------+
648 rows in set (0.02 sec)
--------------------------

Skip the first 3 lines and the last two lines. I would need an output like -

ABDULHADI, ASHRAF M, 2, 1990, 3
ACHANTA, BALA, 2, 1995, 3
ACHANTA, BALA, 2, 1996, 3
Was it helpful?

Solution

You can start with this awk and build on it as you need.

awk '
BEGIN {
    FS = " *[|] *"              # Set the Field Separator to this pattern
    OFS = ","                   # Set the Output Field Separator to ,
}
NF {                            # Skip blank lines
    $1 = $1                     # Reconstruct your input line
    gsub(/^,|,$/,"")            # Remove leading and trailing ,
    lines[++i] = $0             # Add line to array
}
END {
    for(x=4;x<=i-2;x++)         # Skip first three and last two lines
        print lines[x]          # Print line
}' file
ABDULHADI, ASHRAF M,2,1990,3
ACHANTA, BALA,2,1995,3
ACHANTA, BALA,2,1996,3

If your data does not have blank lines then you can remove NF and use NR as key instead of ++i

FS pattern above is zero or more spaces followed by pipe (placed in character class to consider it literal, since it is a meta character) followed by zero or more spaces.

OTHER TIPS

Here is an awk

awk -F" *[|] *" 'FNR==NR {a=FNR;next} FNR>3 && FNR<a-2 {print $2,$3,$4,$5}' OFS=", " file{,}
ABDULHADI, ASHRAF M, 2, 1990, 3
ACHANTA, BALA, 2, 1995, 3
ACHANTA, BALA, 2, 1996, 3

Read the file two times, one to count the lines, one to get the correct output.
If your awk does not work with file{,}, change to file file to read it two times

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top