Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help using awk or some kind of Tool in Unix to Read a file, cut fields and write to a file

Status
Not open for further replies.

ziggy6

Technical User
Jun 24, 2012
9
US
I have a file that I will be reading in and want to extract some of the fields and write it to another file comma delimited. The incoming file is fixed length text and the fields are not separated by any character, the fields are fixed length and I know where each field is located on each record within the file.

An example would be extracting 4 fields from file "journal.txt" , RECNO = Position 1, Length 7, Account # = Position 8, Length 5, TAXABLE-SALE = Position 13, Length 9, Freight = Position 99, Length 9.

Screenshot_2024-08-09_101920_rjppyp.png


The example includes 2 records from the file "journal.txt" , RECNO 70 and 71, RECNO 70 has Act # 01475, Taxable-Sale 91.14 and Freight on RECNO 71 of 340.00

Looking for Results in myfile.txt
000070,01475,91.14,0
000071,01465,0,340.00

Journal File
000007001475 91.14 91.14 97.52 OT-RB 07/01/20240044111
GB002 0000000115:46
^M
000007101465 3709.71 4049.71 OT-RB 07/01/20240044112
MV016 340.00 0000000116:23
^M
 
However, you should post your example files between the [pre]
Code:
[/pre] and [pre]
[/pre] tags so that the spaces are preserved
 
I assume that the record separator ^M is the Carriage Return character 0xD i.e. \r

Then this works for me:

ziggy6.awk
Code:
BEGIN {
  RS = "\r"
  OFS = ","
}

{
  sub(/\s+/, " ", $0)
  
  if (split($0, line, "\n") >= 2) {
    ln1_nr_flds = split(line[1], line1, " ")
    ln2_nr_flds = split(line[2], line2, " ")
    $0 = ""
    if ((ln1_nr_flds == 6) && (ln2_nr_flds == 2)) {
      $1 = substr(line1[1], 1, 7)
      $2 = substr(line1[1], 8, 5)
      $3 = line1[2]
      $4 = 0
    } 
    else if ((ln1_nr_flds == 5) && (ln2_nr_flds == 3)) {
      $1 = substr(line1[1], 1, 7)
      $2 = substr(line1[1], 8, 5)
      $3 = 0
      $4 = line2[2]
    }
     
    print   
  }
}

Output:
Code:
$ awk -f ziggy6.awk ziggy6.txt
0000070,01475,91.14,0
0000071,01465,0,340.00
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top