Roger
Roger

Reputation: 95

UNIX for loop using awk to assign a variable

for i in `cat filename.lst|awk '{print $1}{print $2 > var1}'`
do
echo "$i and $var1"
done

but not working , i have file as

xyz 123
abc 456
pqr 789

expected output:-

xyz and 123
abc and 456
pqr and 789

Upvotes: 0

Views: 782

Answers (2)

Ed Morton
Ed Morton

Reputation: 203512

$ awk '{print $1, "and", $2}' file
xyz and 123
abc and 456
pqr and 789

$ sed 's/ / and /' file
xyz and 123
abc and 456
pqr and 789

If that's not all you want then edit your question to clarify your requirements and provide a more truly representative example.

Upvotes: 0

tripleee
tripleee

Reputation: 189397

You seem to be looking for something like

while read -r i value; do
    var1=$value
    echo "$i and $var1"
done <filename.lst

You want to avoid reading lines with for and the useless use of cat.

Awk cannot manipulate your Bash variables, and Bash has no idea what happens inside your Awk script.

If you absolutely insist on using Awk for this, you want its output to be a string you can safely eval from your shell.

eval "$(awk '{ print "var1=\047" $2 "\047;\n" \
    "echo \"" $1 " and \$var1\"" }' filename.lst)"

The precise definition of "safely" is probably too hard to pin down exactly. In other words, really just don't do this.

Upvotes: 2

Related Questions