0

I have a variable (that contains multiple lines of text) that I'm modifying using awk to replace the whitespace between fields with a comma and I'm trying to save it to another variable. This is what I'm doing at the moment:

VAR2=$(echo "$VAR1" | awk 'END {OFS=","}' 1)

However when I do echo "$VAR2", it prints nothing but an empty line.

SMRV10
  • 3
  • This sounds VERY much like you're using a shell (bash) to manipulate text, calling awk once in a while for specific operations, when you should instead be calling awk once total and using awk instead of shell to manipulate the text. – Ed Morton Mar 04 '22 at 20:36

2 Answers2

4

Your AWK script doesn’t output anything. But you don’t need AWK to replace spaces with commas; assuming you’re using a shell such as Bash, you can use

VAR2="${VAR1// /,}"

or with any shell,

VAR2=$(printf "%s" "$VAR1" | tr -s '[:blank:]' ,)

The former won’t collapse multiple spaces; if that’s important, enable extglob (shopt -s extglob) and use

VAR2="${VAR1//+( )/,}"

If you want to use AWK, you need to print after forcing it to update records with the new output separator:

VAR2=$(printf %s "$VAR1" | awk -v OFS=, '{$1=$1} 1')
Stephen Kitt
  • 434,908
1
var2=$(awk '{gsub(/[[:space:]]+/,",",$0);print }' filename)

output

echo $var2
praveen,ajay,san