user1601716
user1601716

Reputation: 1993

how can you change a column of numbers to a space separated list in bash

How can i take the output of this command...

ps -ef | grep ^apache | grep /sbin/httpd | awk '{print $2}'
16779
16783
16784
16785
16786
16787
16788
16789
16790
16794
16795
16796
16797
16799
16800
16801
16802
16803
16804
16805 

...so a single column of numbers... and transform those numbers into a single line of numbers separated by a " -p "... This would be used for the following...

lsof -p 16779 -p 16783 -p 16784 ... 

Upvotes: 3

Views: 1726

Answers (6)

Jo So
Jo So

Reputation: 26541

Pipe into

sed 's/^/-p /' | tr '\n' ' '

Upvotes: 3

Thor
Thor

Reputation: 47239

If you have it available, pidof would be more convenient:

lsof $(pidof apache | sed 's/^\| / -p /g')

Upvotes: 2

Debaditya
Debaditya

Reputation: 2497

Add the following code to your one liner:

awk '{print $0 " -p "}' | tr '\n' '  ' | awk -F " " '{print "lsof -p "  $0}'

Final code :

ps -ef | grep ^apache | grep /sbin/httpd | awk '{print $2}' | awk '{print $0 " -p "}' | tr '\n' '  ' | awk -F " " '{print "lsof -p "  $0}'

Upvotes: 0

chepner
chepner

Reputation: 532508

In a command substitution, the newlines from the pipeline will be converted to spaces.

pids=$( ps -ef | awk '/^apache/ && /\/sbin\/httpd/ {print $2}' ) )

Then a call to printf can be used to format the options for lsof. The format string is repeated as necessary for each argument contained in pids.

lsof $( printf "-p %s " $pids )

Upvotes: 1

pavel
pavel

Reputation: 377

tmp="lsof "
for i in `ps -ef | awk '/^apache/ && /httpd/ {print $2}'`;
do
 tmp=${tmp}" -p "${i}" "; 
done
echo $tmp

Should do the trick

Upvotes: 1

Steve
Steve

Reputation: 54592

You could pipe into awk:

awk 'BEGIN { printf "lsof" } { printf " -p %s", $1 } END { printf "\n" }'

Result:

lsof -p 16779 -p 16783 -p 16784 -p 16785 -p 16786 -p 16787 -p 16788 -p 16789 -p 16790 -p 16794 -p 16795 -p 16796 -p 16797 -p 16799 -p 16800 -p 16801 -p 16802 -p 16803 -p 16804 -p 16805

Upvotes: 1

Related Questions