Home:ALL Converter>awk inline command and full script has different output

awk inline command and full script has different output

Ask Time:2020-10-22T12:00:32         Author:quyleanh

Json Formatter

I want to count the number of starting space at the beginning of line. My sample text file is following

aaaa bbbb cccc dddd
  aaaa bbbb cccc dddd
    aaaa bbbb cccc dddd
aaaa bbbb cccc dddd

Now when I write a simple script to count, I notice the different between inline command and full script of awk ouput.

First try

#!/bin/bash
while IFS= read -r line; do
    echo "$line" | awk '
        {
            FS="[^ ]"
            print length($1)
        }
    '
done < "tmp"

The output is

4
4
4
4

Second try

#!/bin/bash
while IFS= read -r line; do
    echo "$line" | awk -F "[^ ]" '{print length($1)}'
done < "tmp"

The output is

0
2
4
0

I want to write a full script which has inline type output.
Could anyone explain me about this different? Thank you very much.

Author:quyleanh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64475120/awk-inline-command-and-full-script-has-different-output
James Brown :

Fixed your first try:\n$ while IFS= read -r line; do\n echo "$line" | awk '\n BEGIN { # you forgot the BEGIN\n FS="[^ ]" # gotta set FS before record is read\n }\n {\n print length($1)\n }' \n done < file\n\nOutput now:\n0\n2\n4\n0\n\nAnd to speed it up, just use awk for it:\n$ awk '\nBEGIN {\n FS="[^ ]"\n}\n{\n print length($1)\n}' file\n",
2020-10-22T05:03:21
RavinderSingh13 :

Could you please try following without changing FS. Written and tested it in https://ideone.com/N8QcC8\nawk '{if(match($0,/^ +/)){print RSTART+RLENGTH-1} else{print 0}}' Input_file\n\nOR try:\nawk '{match($0,/^ */); print RLENGTH}' Input_file\n\nOutput will be:\n0\n2\n4\n0\n\nExplanation: in first solution simply using if and else condition. In if part I am using match function of awk and giving regex in it to match initial spaces of line in it. Then printing sum of RSTART+RLENGTH-1 to print number of spaces. Why it prints it because RSTART and RLENGTH are default variables of awk who gets set when a regex match is found.\nOn 2nd solution as per rowboat suggestion simply printing RLENGTH which will take care of printing 0 too without using if else condition.",
2020-10-22T04:31:59
yy