Home > Net >  assign two different variables from same line and loop for every line
assign two different variables from same line and loop for every line

Time:02-15

I am trying to assign variables obtained by awk, from a 2 columned txt file. To a command, which includes every two value as two variables in it.

For example, the file I use is;

foo.txt
10 20
33 40
65 78

my command is aiming to print ;

end=20 start=10
end=40 start=33
end=78 start=65

Basically, I want to iterate the code for every line, and for output, there will be two variables from the two columns of the input file.

I am not an awk expert (I am trying my best), what I could have done so far is this fusion;

while read -r line ; do  awk '{ second_variable=$2 ; first_variable=$1 ; }'  ; echo "end=$first_name start=$second_name"; done <foo.txt

but it only gives this output;

end= start=

only one time without any variable. I would appreciate any suggestion. Thank you.

CodePudding user response:

In bash you only need while, read and printf:

while read -r start end
do printf 'end=%d start=%d\n' "$end" "$start"
done < foo.txt
end=20 start=10
end=40 start=33
end=78 start=65

With awk, you could do:

awk '{print "end=" $2, "start=" $1}' foo.txt
end=20 start=10
end=40 start=33
end=78 start=65

With sed you'd use regular expressions:

sed -E 's/([0-9] ) ([0-9] )/end=\2 start=\1/' foo.txt
end=20 start=10
end=40 start=33
end=78 start=65

CodePudding user response:

Just in Bash:

while read -r end start; do echo "end=$end start=$start"; done <foo.txt
  • Related