rabka
rabka

Reputation: 75

read all text file and put in arguments

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

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

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

Heisenbug
Heisenbug

Reputation: 39164

I think you are looking for xargs. Try this command in the directory where are your .txt files:

cat * | xargs ./read.sh

Alternatively:

./read.sh `cat *`

Upvotes: 1

Related Questions