0

I have a small snippet which gives me some ips of my current network:

#!/bin/bash
read -p "network:" network
data=$(nmap -sP $network | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}')

it returns ip addresses like this

10.0.2.1
10.0.2.15

and so on.

now I want to make them look like this:

10.0.2.1, 10.0.2.15, ...

I'm a total bash noob ,plz help me :)

  • Add in the end of your awk ORS=", " and you will have the result you want, with a small disadvantage (a trailing comma). – George Vasiliou Oct 27 '19 at 23:49
1

If you need exactly ", " as separator, you could use

echo "$data" | xargs | sed -e 's/ /, /g'

or if you are enough with comma as separator, then

echo "$data" | paste -sd, -
|improve this answer|||||
0

You could modify your awk script so that it returns a list of IP addresses delimited by a comma and a space but joining a list of items with a specific delimiter is such a common task that it's better to have a re-usable tool (script, function, compiled program, whatever) to do that.

Several languages (like perl) have such a function built-in. Unfortunately, bash is not one of them....but it's fairly easy to write:

# perl-like join function for bash
join_by() {local d=$1; shift; printf '%s' "$1"; shift ; printf '%s' "${@/#/$d}"; echo;}

Put that in your ~/.bashrc or ~/.bash_profile and you'll always have it available.

This is modelled on the perl join() function, but is named join_by so that it doesn't conflict with the standard join program (which joins lines in files).

The first argument is the delimiter. All remaining arguments are the data to be joined.

For example:

$ data=$'10.0.2.1\n10.0.2.15'
$ join_by ', ' $data
10.0.2.1, 10.0.2.15

This particular usage is not recommended. It relies on the shell word-splitting the un-quoted $data variable on whitespace (spaces, tabs, newlines, etc). That is something that should be avoided where possible...I've included it here only because you are capturing the nmap output into a single string variable.

You should be using an array instead. Like this:

data=( $(nmap -sP "$network" | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}') )

That puts each IP addressed returned by your nmap | awk pipeline into a separate element of the $data array.

here's a contrived example of how you'd join an array with join_by:

$ data=(10.0.2.1 10.0.2.15)
$ join_by ', ' "${data[@]}"
10.0.2.1, 10.0.2.15
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.