Skip to content
Advertisement

Set an external variable in awk

I have written a script in which I want to count the number of columns in data.txt . My problem is I am unable to set the x in awk script. Any help would be highly appreciated.

JavaScript

data.txt file:

JavaScript

Expected output:

JavaScript

My output:

JavaScript

Advertisement

Answer

You just cannot import variable set in Awk to a shell context. In your example the value set inside x containing NF will be not reflected outside.

Either you need to use command substitution($(..)) syntax to get the value of NF and use it later

JavaScript

Now x will contain the column count in each of the line. Note that you don’t need to use -F' ' which is the default de-limiter in awk.

Besides your requirement can be fully done in Awk itself.

JavaScript

Here the NF{..} is to ensure that the actions inside {..} are applied only to non-empty rows. The for each row we print the length and append the extension .txt along with it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement