1

please look at here to read from a file line by line,So I use the first answer and works:

First answer:

The following (save as rr.sh) reads a file from the command line:

#!/bin/bash
while read line
do
    name=$line
    echo "Text read from file - $name"
done < $1
Run the script as follows:

chmod +x rr.sh
./rr.sh filename.txt

My question is If I want to read another file line by line , What I should do ? For example this code :

The following (save as rr.sh) reads a file from the command line:

#!/bin/bash
#this read refers to filename.txt
while read line 
do
    name=$line
    echo "Text read from file - $name"
done < $1
.
.
.
#this read refers to file2.txt
while read line 
do
    name=$line
    echo "Text read from file - $name"
done < $1
Run the script as follows:

How I can write this?

Community
  • 1
  • 1
alex
  • 1,319
  • 3
  • 16
  • 28

2 Answers2

2

Your use of $1 implies the name of the file to read from is passed as the first argument to your script. To read from two different files, pass both names as arguments:

rr.sh file1.txt file2.txt

and use $2 for the input redirection to the second loop.

#!/bin/bash
while read line 
do
    echo "Text read from file - $line"
done < "$1"

while read line 
do
    echo "Text read from file - $line"
done < "$2"

You can refer to as many command line arguments as you like. After the ninth argument ($9), you must use braces to enclose the number (so for the tenth, use ${10}).

chepner
  • 497,756
  • 71
  • 530
  • 681
2

what you need to do is to add a 'for' loop:

#!/bin/bash

for file; do
    while read line; do
        echo "Text read from $file - $line"
    done < "$file"
done

then run it as: ./rr.sh file1 file2 file3 otherfile*

lihao
  • 583
  • 3
  • 6