0

The script should read input from a file (for example input.txt), store each line(N number of lines) of a file in a separate variable, and use each variable uniquely at different places.

For example , a file has 4 lines- A B C D these should be stored in 4 variables.

  • 1
    In bash, it would be more natural to use an array e.g. mapfile -t arr < input.txt then access the individual variables as "${arr[0]}", "${arr[1]}" etc. – steeldriver Jul 12 '18 at 11:52
  • I think you need to clarify "use each variable uniquely at different places". This is simple if your input is fixed as a 4 line file but will it always be? What criteria should be used to determine which line should be used where? – Jesse_b Jul 12 '18 at 12:08
  • @Jesse_b , lets say the file would have first line as FirstName, second line as SecondName, third line as OrgName , and fourth line as CnName, (lets assume for now that this is going to the only order)now the script should read each line and store each in a variable . Now I want each variable to be echoed(appened to be precise, echo command) to a standard output format in a new file(which in real world is a config file). But, still I want the loop/logic to be independent of the number of lines in input.txt. – OdbovViktor Jul 12 '18 at 13:43
  • It sounds like you're asking for an impossible task. If each line needs to correspond to a specific metric you must know how many lines are in your input and you should be at least reasonably sure the input is formatted in the way you're script needs it to be in order to function – Jesse_b Jul 12 '18 at 13:48
  • 1
    Please update the question with further information about why you need to do this. From comments it sound like it's not actually needed to read them into separate variables, but as if a fairly simple awk script could do what you'd like to do (whatever it is). – Kusalananda Jul 12 '18 at 13:51
0

the following will load each line of /tmp/file into an array, so line 1 would be accessible via the variable ${array[0]} and so on.

#!/bin/bash
IFS=$'\n' array=($(cat /tmp/file))
0

As Kusalananda points out this sounds like an x-y problem.

A possible awk solution to your issue would be:

awk 'BEGIN{ RS = ""; FS = "\n"}{print "First name:",$1,"Second name:",$2,"Org name",$3,"CN name:",$4}' input

If you are set on using shell variables I think you need something like this:

#!/bin/bash

input=/path/to/input

mapfile -t array <"$input"

# If you don't have bash v3 use this instead of mapfile
# OLDIFS=$IFS
# IFS=$'\n'
# array=($(cat input))
# IFS=$OLDIFS

echo "First name: ${array[0]}, Second name: ${array[1]}, Org name: ${array[2]}, CN name: ${array[3]}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.