Home > database >  How to store the content of reading file after AWK pipe correctly to a variable [duplicate]
How to store the content of reading file after AWK pipe correctly to a variable [duplicate]

Time:09-29

I am trying to read values from a file and store them in 3 variables and then echo them but is giving me empty output

list file contains smith:P@assWord:IP

commands :

user1= cat list| awk -F ':' '{print $1;}'
pass1= cat list| awk -F ':' '{print $2;}'
IP1= cat list| awk -F ':' '{print $3;}'
echo $user1,$pass1, $IP1

But I get empty output from echo.

Expected output : smith,P@assWord,IP

Thanks in Advance.

CodePudding user response:

You need to execute commands and assign result of the commands to the variables but your syntax doesn't do that.

Use this one instead:

user1=$(cat list| awk -F':' '{print $1}')
pass1=$(cat list| awk -F':' '{print $2}')
IP1=$(cat list| awk -F':' '{print $3}')
echo $user1,$pass1,$IP1

Key thing is to use command substitution to execute command and assign its result to a variable. You can read more about it here: https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html

Update: Look at Jetchisel's answer as he provided more efficient way to do this.

Update2: As you mentioned that you need to read and print multiple lines, here is the code you can use:

while read line;
  do echo $line | awk -F':' '{printf "%s,%s,%s\n", $1,$2,$3} ';
done < list

CodePudding user response:

First paste your script at https://shellcheck.net for validation/recommendation.

If if there is only one line in a file then the built in read should suffice. Avoid the infamous all time favorite UUoC.

IFS=: read -r user1 pass1 Ip1 < list

Check the values of the variables.

declare -p user1 pass1 Ip1

Print the desired output. ( An alternative to echo )

printf '%s,%s,%s\n' "$user1" $pass1" "$Ip1"

Assigning to a variable the combined variables

printf -v new_var '%s,%s,%s' "$user1" "$pass1" "$Ip1"

declare -p new_var

The above solution avoids reading the file each time you assign to a variable, unlike the use of ProcSub.

  •  Tags:  
  • bash
  • Related