---
title: "shell读文件"
author: "vergilwang"
date: "2013-06-26T15:00:00Z"
tags: []
categories: ["编程语言"]
slug: "shell"
draft: false
lastmod: "2014-02-15T14:09:46Z"
id: 2011165
url: "https://vergilwang.iteye.com/blog/2011165"
---

## shell读取文件的每一行

写法一：

\----------------------------------------------------------------------------

#!/bin/bash

 

while read line

do

echo $line

done &lt; filename(待读取的文件)

\----------------------------------------------------------------------------

 

写法二：

\----------------------------------------------------------------------------

#!/bin/bash

 

cat filename(待读取的文件) | while read line

do

echo $line

done

\----------------------------------------------------------------------------

 

写法三：

\----------------------------------------------------------------------------

for line in \`cat filename(待读取的文件)\`

do

echo $line

done

\----------------------------------------------------------------------------

 

说明：

for逐行读和while逐行读是有区别的,如:

$ cat file

1111

2222

3333 4444 555

 

$ cat file | while read line; do echo $line; done

1111

2222

3333 4444 555

 

$ for line in $(&lt;file); do echo $line; done

1111

2222

3333

4444

555

[#Shell](http://hi.baidu.com/tag/Shell/feeds)