Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

linux - How can I trim white space from a variable in awk?

Suppose $2 is my variable. I have tried going from

awk -F, '{print $2 ":"}'

to

awk -F, '{print gsub(/[ ]+$/, "", $2) ":"}'

But it goes from printing something to printing nothing at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're printing the result of the gsub, but gsub does an in-place modify of $2 instead of returning a modified copy. Call gsub, then print:

awk -F, '{gsub(/[ ]+$/, "", $2); print $2 ":"}'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...