AWK: Remove All Blank Spaces From String / Field

In awk, you can remove all blank spaces from a string or field using the gsub function.

For example, to remove all blank spaces from the first field of each record in a file:

awk '{gsub(/ /,"",$1); print}' file.txt

In this example, the gsub function replaces all occurrences of a space character (represented by / /) with an empty string (represented by "") in the first field ($1) of each record. The modified record is then printed.

You can also use the gsub function to remove all blank spaces from a string stored in a variable. For example:

awk 'BEGIN{string="Hello World"; gsub(/ /,"",string); print string}'

This will print HelloWorld to the console.

(https://restorehealthky.com/)

Leave a Comment