Reputation: 75
How do we read all text files and put in arguments so we can process it for variable?
1.txt -->100
2.txt -->200
..
9.txt -->900
$ ./read.sh 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt
read.sh:
$file1=$1
$file2=$2
...
$file9=$9
But it inserts "1.txt" instead 100, how we can get the value of file instead the name of file?
Upvotes: 1
Views: 390
Reputation: 200203
Not sure if I understand your question correctly. If you want to put the content of the files you pass as arguments to the script into the variables $file1
, $file2
, etc. you should make read.sh
look like this:
file1=$(<"$1")
file2=$(<"$2")
...
file9=$(<"$9")
Note that when assigning a value to a variable you must use the variable name without a leading $
.
A more general solution (provided you're using bash 4) might look like this:
declare -A files
while [ -n "$1" ]; do
files[$1]=$(<"$1")
shift
done
declare -A
creates an associative array (or dictionary) where you can store name→value mappings, e.g. filename→content.
Upvotes: 2