This will do what you said you want:
$ cat tst.sh file="${!#}" cols=( " $@ " ) unset cols[$(( $# - 1 ))] awk -v cols="${cols[*]}" ' BEGIN { split(cols,c) FS=OFS="|" } { for (i in c) { gsub(/^[[:space:]]+|[[:space:]]+$/,"",$(c[i])) sub(/^$/,"NULL",$(c[i])) } print }' "$file" $ ./tst.sh 2 5 file 1|2016-01|00000321|12|2016-01|00000 2|2016-02|000000432|13|2016-01|00000 3|2017-03|000004312|54|NULL|00000 4|NULL|000005|2016-02|0000 5|2017-05|00000543|12|2016-02|0000
but if what you REALLY wanted was to work on ALL fields instead of specific ones, then, of course, there was a simpler solution.
Never do cmd file > tmp; mv tmp file cmd file > tmp; mv tmp file way, always do cmd file > tmp && mv tmp file instead (pay attention to && ) so that you only overwrite the original file if the command is successful. Also, always specify your shell variables if you do not have a very specific goal, without doing this and not fully understanding all the consequences, so use "$file" , not $file . Google it.
source share