Ashish Tripurwar
Ashish Tripurwar

Reputation: 161

How read file line by line if I don't know the number of fields?

filename.csv contains:

public|database|subs_vw|5|6|9|3|10|1

Basically my script is this:

#!/bin/bash

function replace_col(){
    prep_cmd="awk -F\| 'BEGIN {srand()}
                            {sub(\$$1,\"Sa\"int(rand()*100000)\"GA\"); print}' \
                            $tablename.data > $tablename.ano"
    echo $prep_cmd
    eval $prep_cmd
}

tablename="subs_vw"

gawk 'BEGIN {FS="|"}
      { for(i=4;i<=NF;i++)
        var="echo $i"
        echo $var
        replace_col $i
      }' < filename.csv

Giving file as input it takes value correct but is not calling a function. Basically I want replace all specified columns e.g. 5|6|9|3|10|1 by a random number. Can anybody help me out please?

Upvotes: 0

Views: 69

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

A simple for loop can serve the purpose.

gawk 'BEGIN {FS="|"}
            { print "SCHEMA :" $1
              print "DATABASE :" $2
              print "TABLENAME :" $3
              for(i=4;i<=NF;i++)
                   print "COLUMN :" $i

             }' filename.txt

Here NF is number of fields, columns in each row.

for(i=4;i<=NF;i++)

will iterate from the 4th column to the end of the columns.

EDIT

Replacing |5|6|9|3|10|1 with random numbers.

 awk -F\| '{OFS = "|";for(i=4;i<NF;i++) $i= int(rand()*100); print $0 }' inputfile

Will produce an ouput as

public|database|subs_vw|23|29|84|15|58|1

what it does

$i= int(rand()*100) the ith field is replaced by a random number.

rand() returns a random number within 0 and 1

int() truncates the value to integer

print $0 prints the entire record.

EDIT2

change 5 6 9 10 to random values

 $awk -F\| 'BEGIN{OFS = "|"; indx[1]=5; indx[2]=6; indx[3]=9; indx[4]=10 }{for(i in indx) if(indx[i]<=NF)  $indx[i]=int(rand()*100); print $0 }' file
    public|database|subs_vw|5|29|84|3|10|15|23

Upvotes: 2

Related Questions