Easy Tutorial
❮ Android Tutorial Sdk Problem Solve Db Solutions ❯

SHELL Read the content of each line of a file and output it

Category Programming Techniques

Assuming the file being read is the test.txt file in the current directory, with the following content:

Google
tutorialpro
Taobao

Example 1

#!/bin/bash

while read line
do
    echo $line
done < test.txt

Execution output result:

Google
tutorialpro
Taobao

Example 2

#!/bin/bash

cat test.txt | while read line
do
    echo $line
done

Execution output result:

Google
tutorialpro
Taobao

Example 3

for line in `cat test.txt`
do
    echo $line
done

Execution output result:

Google
tutorialpro
Taobao

There is a difference between reading line by line with for and while:

$ cat test.txt
Google
tutorialpro
Taobao

$ cat test.txt | while read line; do echo $line; done
Google
tutorialpro
Taobao

$ for line in $(&lt;test.txt); do echo $line; done
Google
tutorialpro
Taobao

** Click here to share notes

Cancel

-

-

-

❮ Android Tutorial Sdk Problem Solve Db Solutions ❯