Update a field using awk and keep the formatting.

Look at this simple example.

echo "  2 4 6" | awk '{$2+=3;$3-=1}1'
2 7 5

Is there a simple way to update a field and at the same time keep the formatting?

I would like to get it like this

  2 7 5

I have tested both sub and gsub , it reformat too.

Anytime you reset a numbered field (such as $2=x or sub(regex, replacement, $n) ) for n not equal to 0), $0 is recalculated. For the general case, you could try something like:

(	printf "  2 4 6\n"
	printf "1\t3\t7\t\n"
	printf "\t xyz\t 2\t 3 with more fields\n"
) | awk '
{	n = split($0, delims, /[^[:space:]]*/)
	$2+=3
	$3-=1
	for(i = 1; i <= n; i++)
		printf("%s%s", delims, $i)
	print ""
}'

which produces the output:

  2 7 5
1	6	6	
	 xyz	 5	 2 with more fields

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

The loop printing the modified lines and the following print command can be simplified to a single printf command if you know that there are always three fields.

1 Like

Not a quick and short solution, but it works :slight_smile:
I see that you store the number of spaces in an array, and then add i back.