Multiple lines combined into one for netstat (or ls)

Hello

So I understand when I do the following

used_ports=$(netstat -nat |cut -d : -f 2 |cut -d ' ' -f 1)

that the output will look like this

Active Proto 5298 22 631 55012 56093 39672 43196 56619 39677 36103 
38453 41413 56137 37902 41410 41414 43195 38426 49253 38420 34273 
49241 56124 38433 34935 56121 49255 38451 45457 58900 49240 34274 
45535 54558 49242 41411 36104 38452 49254 59107

But I actually want to then grep for individual ports -- impossible if all are on the same line. I need to make sure that 10 or 15 consecutive ports I need are not in use. easy to do if I call netstat 10-15 times and grep for each port seperately, but that seems expensive. Is there a way to store the netstat output and then ensure the ports I need are not in use?

I actually have similar problems with ls occasionally, so explaining why the output gets stuck on a single line, and then how to work with it in general would be useful to me.

For one, quotes might prove helpful:

[house@leonov] used_ports=$( netstat -nat | cut -d: -f2 | cut -d' ' -f1 ); echo $used_ports
Active Proto 60224 2049 42344 40461 815 111 631 [...]

[house@leonov] used_ports=$( netstat -nat | cut -d: -f2 | cut -d' ' -f1 ); echo "$used_ports"
Active
Proto
60224
2049
42344
40461
815
111
631
[...]

Alternatively, "extended grep-ing" would be an option:

[house@leonov] echo $used_ports | grep -o -E '(111|815) '
815
111
1 Like