使用awk和for循环逐行读取文件

时间:2014-01-28 09:24:38

标签: bash for-loop awk hp-ux

文件包含编译器生成的警告

warnings.txt(有8行)

 Line1  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 1657: error #4296-D: arithmetic operation on boolean type
 Line2{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0);
 Line3
 Line4  
 Line5  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 4136: warning #3348-D: declaration hides variable "err" (declared at line 3
 Line6 700)
 Line7          { int err = SSL_get_error(soap->ssl, r);
 Line8                ^  

我想使用awk逐行读取此文件,因为while循环需要很长时间来处理

我尝试过两种方式:

for line in `awk '{print $0}' warnings.txt`
do
  echo $line
done

for line in `awk '{BEGIN{ORS="\n";}{print $0}' warnings.txt`
do
  echo $line
done

预期输出:

与上述相同(即逐行文件的内容)

 Line1  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 1657: error #4296-D: arithmetic operation on boolean type
 Line2{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0);
 Line3
 Line4  
 Line5  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 4136: warning #3348-D: declaration hides variable "err" (declared at line 3
 Line6 700)
 Line7          { int err = SSL_get_error(soap->ssl, r);
 Line8                ^  

我的输出:

"/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp",
line
1657:
error
#4296-D:
arithmetic
operation
on
boolean
type
{
return
soap->count
-
soap->buflen
+
soap->bufidx
-
(soap->ahead
!=
0);
"/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp",
line
4136:
warning
#3348-D:
declaration
hides
variable
"err"
(declared
at
line
3
700)
{
int
err
=
SSL_get_error(soap->ssl,
r);
^

谢谢

3 个答案:

答案 0 :(得分:2)

使用read内置

while read -r line; do
    echo "$line"
done < warning.txt

答案 1 :(得分:1)

根据您发布的问题,以下是使用awk阅读warnings.txt并按原样重新生成文件的方法:

$ awk '1' warnings.txt
 Line1  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 1657: error #4296-D: arithmetic operation on boolean type
 Line2{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0);
 Line3
 Line4
 Line5  "/Project/user/XYZ/gsoap/gsoap-2.8.9/gsoap/stdsoap2.cpp", line 4136: warning #3348-D: declaration hides variable "err" (declared at line 3
 Line6 700)
 Line7          { int err = SSL_get_error(soap->ssl, r);
 Line8                ^

显然你可以用cat而不是awk来做到这一点。如果您还有其他任何想要处理该文件内容的内容,请告诉我们(通过更新您的问题并提供预期的输出和解释),以便我们为您提供帮助。

答案 2 :(得分:-3)

你可以这样做:

代码:

ifsold="$IFS"
IFS="
"
for line in `cat warnings.txt` ; do
    echo "line: $line"
done
IFS="$ifsold"