1

while it may seem simple i can't figure this and and i don't wanna complicate it with python. I'm trying to get 2 variables from a "cat file.txt" in a loop. For just one variable it's simple:

   for i in `cat mylist`; do
     echo ${i}
done

In this example we have just one word per line.

I need to make 2 separate variables from a line that contains 2 words/numbers per line separated by tab or space.

root@hostname#cat iplist 
192.168.0.1 device1

192.168.0.2 device2

192.168.3.2 device3
0

1 Answer 1

3

Use a while loop, and let read split the variables:

while read -r a b; do
   # do stuff with "$a" and "$b"
done < file
Sign up to request clarification or add additional context in comments.

8 Comments

what does -r flag do ?
It prevents the backslashes to be parsed, so if you have a value with \t, with -r it will remain like this in the variable, without -r it will be converted to a tab.
Can't adapt it to my needs(meaning i can't figure it out) , i already saw this syntax used around.
@user000001: without the -r the characters \t get converted to t, not a tab (try it). Same with others like four characters \r\n get converted to rn.
@user000001: agreed, the code you posted is absolutely right. I have always wondered why read does the `\` stripping by default. SFAIKT it has always done so (goes back to the 1980s), but I cannot find a source which says why it was done like 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.