1

I have a list file which contains:

1.1.1.1:50
1.1.1.2:60
1.1.1.3:70

I am trying to make two variables and execute an internal application to hash the first column with the second one. What I did is these loops, but they give me 9 possibilities and I need only three:

This is my script

#!/bin/bash
for a in $(cat list | cut -d ":" -f 1 )
do
    for b in $(cat list | cut -d ":" -f 2 )
    do
        echo $a,$b # this is example 
    done
done

1 Answer 1

1
sed 's/:/ /' list |
while read ipv4 port
do
    echo "IPv4 address: $ipv4; Port number: $port"
done

The only thing to be aware of is that if you set other variables in the loop, they will be run in a subshell and won't affect the rest of the script. There are ways around that if need be (look up process substitution).

Sign up to request clarification or add additional context in comments.

6 Comments

... or simply sed -r 's/(.*):(.*)/IPv4 address: \1; Port number: \2/' list
@hek2mgl: Since the echo in the original is marked as "this is an example", the same applies to my answer. You're right; if the objective is simply to echo data to standard output, there's no need for the loop. It's likely that the objective is to run wget or curl or telnet or something using the IP address and port number, in which case the simple sed substitution isn't sufficient. The port numbers don't really give the game away — they're fake too, for all practical purposes. (The question says "running application to hash the two values".)
Good point, the echo is just an example, you are right. Just let me add that we can make use of $IFS instead of sed: while IFS=":" read ip port ; do echo "$ip -> $port" ; done < list
Yes, you can use IFS too. I tend to use sed or similar techniques in preference to tinkering with IFS. I find it more robust and the cost negligible. There are those who insist that you should do everything in the shell that can possibly be done in the shell (rather than use the shell to execute an external command) to avoid overhead. That's fine — but I often find the concern for 'efficiency' over-rated and the reduced clarity of the script less helpful. YMMV.
That's fine. I'm not pedantic about that. Just thought the IFS solution would be a good alternative in this case. The basic essence is to use while read over for .. in, and you showed that!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.