1

I am using below command to remove line feeds with in field values.This sample commmand created for file having 3 attributes.

awk -F\| '{while(NF<3 && getline p)$0=$0 p}1'

My input filess having different number of attributes, so I want to parameterize number of attributes value in AWK command. I tried like below but getting error.

NoAttributes=12
awk -F\| '{while(NF<$NoAttributes && getline p)$0=$0 p}1'

Error Details:

awk: Field is not correct.

The input line number is 1.

The source line number is 1.

3

To set an awk variable on the command line, use -v variable=value:

awk -v attrs=2 '{ ... NF < attrs && ... }'

You may also access environment variables by using ENVIRON["variable"] in the awk code:

export attrs=2
awk '{ ... NF < ENVIRON["attrs"] && ... }'

or,

attrs=2 awk '{ ... NF < ENVIRON["attrs"] && ... }'

or,

env attrs=2 awk '{ ... NF < ENVIRON["attrs"] && ... }'

The last two variations would not set attrs in the invoking environment, only for the awk program (and any processes it may possibly start).

A third way is to give variable=value as a "filename" argument:

awk '...' msg="hello" file1 file2 msg="good bye" file3 file4

This would set the awk variable msg to the string hello before starting to process the file file1. It would retain that value until the value is change to good bye just before processing file3. Note that variables set in this way would not be available inside any BEGIN block in the awk code.

Injecting shell variables directly into the awk code by means of a variable expansion in the string that constitutes the code is not a good way of transferring data into an awk program, and should be avoided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.