I would like to solve the problem below using AWK.If any other solutions are possible using languages such as sed orPerl, that would also be much appreciated.Below is the input:U,N,UNIX,000,A,5N,P,SHELL,111,B,6I,M,UNIX,222,C,7X,Y,BASH,333,D,8P,R,SCRIPT,444,E,9I want the output as below:U,N,,,A,5N,P,,,B,6I,M,,,C,7X,Y,,,D,8P,R,,,E,9Please also note that: the total number of fields per line isunknown to me. I only know that fields 3 and 4 are to be blanked.
How can I blank the nth to mth field using the awk command?
awk;sed;perl
To scalably blank all fields from the nth to the mth in an awk command, you shouldn't hardcode the values; you should use a for loop:awk 'BEGIN { FS = ,; OFS = ,} {for (i = 3; i <= 4; i++) { $i =  }; print}' inputfileIf you want to blank out a different range, adjust the values 3 and 4 in the above code.Explanation:The BEGIN { ... } block is processed before looking at any of the lines of the file.OFS sets the output field separator, and FS sets the field separator for input.  We want them both to be commas.The for loop is just like C syntax.  In this case it performs the following { code block } for i as 3 and as 4.The $i deserves mention because it is entirely unlike shell syntax.  In shell scripting, the name of a variable must be prefixed with $ to expand to the value of the variable.  Not so in awk.  In awk, i by itself expands to its value3 or 4 in this caseand the $ followed by a number means the field in that numbered position.  So $i =  sets the ith field to a blank string.Then the print command, given without arguments, defaults to printing the entire line.  Actually it takes all the fields of the line as delimited by FS, and as modified by any previous commands, and prints them all, separated by OFS and followed by a newline at the end.An equivalent shorter command:I feel that the above command is the cleanest and most easily extensible if you are going to include it in a script.  It is very explicit about what it is doing and very readable.  Plus, the entire thing can be broken out to a standalone awk script without change; something that can't be done automatically when using -v and -F switches to your awk invocation.  (That's no reason not to use them, of course.  Just something to be aware of.)For a one-off usage especially, I would use the following:awk -F, -v OFS=, '{for (i = 3; i <= 4; i++) { $i =  }; print}' inputfileThe -F switch sets the value of FS.  The -v switch allows you to set values of awk variables on the command line.On a more general note, the -v switch can be extremely useful for passing shell variables in as awk variables: -v myawkvar=$myshellvar and for changing the runtime behavior of a standalone awk script that you pull from a script file with the -f scriptname option at the command line.