Methods for simultaneously reading multiple files under the shell

Source: Internet
Author: User
Tags printf

1. Single File read

Under the shell script, you can read files by rows in a variety of ways, as follows:

For line in ' Cat ${input_filename} '

Todo

Echo $line

Done

While Read line

Todo

Echo $line

Done < ${input_filename}

The second way is to redirect files to standard input

2. Multiple file reading methods

How do you achieve simultaneous reading of multiple files?

We can continue to use the file redirection feature in bash to redirect files to a specific file descriptor with the following syntax:

N

N>file

N>>file

N<>file

The n here represents the file descriptor for opening file files, similar to the FD in other programming languages, and if n is not specified, the default behavior is as follows:

  

>file #same as 1>file

<>file #same as 0<>file

We can open the file you want to redirect by using the EXEC command:

EXEC 7

EXEC 8

We can then read the contents of the corresponding file through the Read command:

Read Data <&7 #使用符合是为了区分7是文件描述符, not filename

Read Data <&8

Close File

EXEC 7

EXEC 8

The sample code for multiple file reads is as follows:

Readfiles () {

Local fd1=7

Local fd2=8

Local file1=$1

Local file2=$2

Local count1=0

Local count2=0

Local eof1=0

Local eof2=0

Local data1

Local data2

# Open files.

EXEC 7< $file 1

EXEC 8< $file 2

while [[$eof 1-eq 0 | | $eof 2-eq 0]]

Todo

If read data1<& $FD 1; Then

Let count1++

printf "%s, line%d:%sn" $file 1 $count 1 "$data 1"

Else

Eof1=1

Fi

If read data2 <& $FD 2; Then

Let count2++

printf "%s, line%d:%sn" $file 2 $count 2 "$data 2"

Else

Eof2=1

Fi

Done

}

#read File1 and File2

Readfiles file1 file2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.