Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK: don't want to print a space at end of line ...

Status
Not open for further replies.

cptk

Technical User
Mar 18, 2003
305
US
...but I want to keep the space between the successful words I do find and still preserve the newline.

Anotherword, I want the output from each line to appear on the same line, spearated by a space, with the last word having no space at the end of line.

My Input Data:

1dog 2dog 3bird
5dog 4bird 4dog

Desired Output:

1dog 2dog <--no space at end of line
5dog 4dog <--no space at end of line

awk '{for(i=1;i<=NF,++i)if($i ~/dog/)printf("%s ",$i);print""}'


I know there are different ways to put a space between each successful $i (i.e. - printf("%s$s", $i,OFS) ), but my problem is when the line is finished, I don't want the last space at end of each line.

how can I do this??


 
awk '{s="";for(i=1;i<=NF;++i)if($i ~/dog/)s=s" "$i;print substr(s,2)}' /path/to/input

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Thanks PHV ...
that's a nice way to trim leading whitespace. I was going to go about it from the trailing-side with the length(s)-1 approach within the substr. Your way is cleaner!

 
awk '{ print $1 " " $2 }' dogbird.txt


Kind Regards
Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top