In: Computer Science
In bash how can I read an input file and create
variables for specific lines and columns from the input
file?
For example I have
Q W E R
T Y U I
A S D F
So if I wanted to make a variable where
Variable = U, how would I create it.
I have created a input file sample.txt as shown below.
Now in the file 'main.sh', I have written the bash script as below
#!/bin/bash
while read line
do
# storing each line of input file as an array in variable 'var'
var=($line)
# to print each line in the file stored in variable var
echo ${var[*]}
# to print a specific word in the line(here i have printed 3rd word in each line)
echo ${var[2]}
done<sample.txt
OUTPUT:
Suppose I want to print a specific in the file and a specific word in that line(I am using a variable 'i' to achieve the same by incrementing it through each iteration of the while loop)
#!/bin/bash
i=1
while read line
do
# storing each line of input file as an array in variable 'var'
var=($line)
# to print specific line in file (say line 2) and a specific word(say 3rd word) in that line
if [ $i -eq 2 ]; then
echo ${var[*]}
echo ${var[2]}
fi
i=$(($i+1))
done<sample.txt
OUTPUT: