user2512450
user2512450

Reputation: 41

Bash for loop - change variable name

I have a for loop that takes a CIDR that contains an illegal character for file names ("/").

part of the command is to save the output with the name of the CIDR.

for i in $(more subnets.lst);do shodan download $i-shodan net:$i;done

the download argument is followed by the result of the more command, which are the CIDR (192.168.21.0/24).

is there a way in bash to rename a variable while the loop is running ? I remember doing this years back in batch files by subtracting from the str length, but that won't help me as I just need to replace the "/" with a "-"(or any other compliant char.

Upvotes: 1

Views: 577

Answers (2)

user2512450
user2512450

Reputation: 41

I worked it out for myself:

for i in $(more subnets-test);do shodan download $(echo $i | tr "/" "-") net:$i;done

Upvotes: 1

heemayl
heemayl

Reputation: 41987

You can do this with using bash Parameter Expansion:

$ echo $var
192.168.21.0/24

$ echo "${var//\//-}"
192.168.21.0-24

So in your command, just use "${i//\//-}" whenever needed without changing the original value of $i. If you want to set variable i to the new value:

i="${i//\//-}"

On a side note, use while loop to read lines from a file, not cat, more or brothers, like:

while IFS= read -r line; do ....; done

Upvotes: 7

Related Questions