Home > Back-end >  how to assign each of multiple lines in a file as different variable?
how to assign each of multiple lines in a file as different variable?

Time:01-04

this is probably a very simple question. I looked at other answers but couldn't come up with a solution. I have a 365 line date file. file as below,

01-01-2000
02-01-2000

I need to read this file line by line and assign each day to a separate variable. like this,

d001=01-01-2000
d002=02-01-2000

I tried while read commands but couldn't get them to work.It takes a lot of time to shoot one by one. How can I do it quickly?

CodePudding user response:

Trying to create named variable out of an associative array, is time waste and not supported de-facto. Better use this, using an associative array:

#!/bin/bash

declare -A array

while read -r line; do
    printf -v key 'dd' $((  c))
    array[$key]=$line
done < file

Output

for i in "${!array[@]}"; do echo "key=$i value=${array[$i]}"; done
key=d001 value=01-01-2000
key=d002 value=02-01-2000

CodePudding user response:

Assumptions:

  • an array is acceptable
  • array index should start with 1

Sample input:

$ cat sample.dat
01-01-2000
02-01-2000
03-01-2000
04-01-2000
05-01-2000

One bash/mapfile option:

unset d                             # make sure variable is not currently in use
mapfile -t -O1 d < sample.dat       # load each line from file into separate array location

This generates:

$ typeset -p d
declare -a d=([1]="01-01-2000" [2]="02-01-2000" [3]="03-01-2000" [4]="04-01-2000" [5]="05-01-2000")

$ for i in "${!d[@]}"; do echo "d[$i] = ${d[i]}"; done
d[1] = 01-01-2000
d[2] = 02-01-2000
d[3] = 03-01-2000
d[4] = 04-01-2000
d[5] = 05-01-2000

In OP's code, references to $d001 now become ${d[1]}.

CodePudding user response:

A quick one-liner would be:

eval $(awk 'BEGIN{cnt=0}{printf "d%3.3d=\"%s\"\n",cnt,$0; cnt }' your_file)

eval makes the shell variables known inside your script or shell. Use echo $d000 to show the first one of the newly defined variables. There should be no shell special characters (like * and $) inside your_file. Remove eval $() to see the result of the awk command. The \" quoted %s is to allow spaces in the variable values. If you don't have any spaces in your_file you can remove the \" before and after %s.

  •  Tags:  
  • bash
  • Related