ShellScript(11) - read a File

 

데이터 파일을 만든 후 ShellScript에서 사용하는 방법을 알아보겠습니다.


예제.1 - Read a File

$ vi read_file.sh
1
2
3
4
5
#!/bin/bash
file='book.txt'
while read line; do
        echo $line
done < $file


$ vi book.txt
1
2
3
4
1. Pro AngularJS
2. Learning JQuery
3. PHP Programming
4. CodeIgniter 3


$ ./read_file.sh
Pro AngularJS
Learning JQuery
PHP Programming
CodeIgniter 3


예제.2 - Reading file content from command line

$ vi company.txt
1
2
3
4
5
Samsung
Nokia
LG
Symphony
iphone
$ while read line; do echo $line; done < company.txt
Samsung
Nokia
LG
Symphony
iphone


예제.3 - Reading file content using script

$ vi readfile3.sh
1
2
3
4
5
6
7
8
#!/bin/bash
filename='company.txt'
n=1
while read line; do
# reading each line
    echo "Line No. $n : $line"
    n=$((n+1))
done < $filename
$ ./readfile2.sh
Line No. 1 : Samsung
Line No. 2 : Nokia
Line No. 3 : LG
Line No. 4 : Symphony
Line No. 5 : iphone


예제.4 - Passing filename from the command line and reading the file

$ vi readfile4.sh
1
2
3
4
5
6
#!/bin/bash
filename=$1
while read line; do
# reading each line
    echo $line
done < $filename
$ ./readfile4.sh company.txt
Samsung
Nokia
LG
Symphony
iphone


예제.5 - Reading file by omitting backslash escape

-r 옵션을 주면 \ (escape) 문자를 그대로 출력할 수 있습니다.

$ vi readfile5.sh
1
2
3
4
5
#!/bin/bash
while read -r line; do
# Reading each line
    echo $line
done < company2.txt
$ vi company2.txt
1
2
3
4
5
\Samsu\ng
\Nokia
\LG
\Symphony
\Apple
$ ./readfile5.sh company2.txt
\Samsu\ng
\Nokia
\LG
\Symphony
\Apple