开发者

Why awk '{ print }' doesn't start a new line but loops on space char

I have this shell script

#!/bin/bash

LINES=$(awk '{ print }' filename.txt) 
for LINE in $LINES; do
  echo "$LINE"
done

And filename.txt has this content

开发者_如何转开发
Loreum ipsum dolores 
Loreum perche non se imortale

The shell script is iterating all spaces of the lines in filename.txt while it is supposed to loop only those two lines.

But when I type the "awk '{ print }' filename.txt" in terminal then it loops ok. Any explanations?

Thanks in advance!


The $(...) construct absorbs all the output from awk as one large string, and then for LINE in $LINES splits on whitespace. You want this construct instead:

#! /bin/sh

while read LINE; do
    printf '%s\n' "$LINE"
done < filename.txt


The other answers are good, another thing you can do is temporarily change your IFS (Internal Field Separator) variable. If you update your shell script to look like this:

#!/bin/bash

IFS="
"
LINES=$(awk '{ print }' filename.txt) 
for LINE in $LINES; do
  echo "$LINE"
done

This updates the IFS to be a newline instead of ' ' which should also do what you want.

Just another suggestion.


You need to loop over LINES as an array as all lines are stored as an array there.

Here's an example how to loop over the lines:

http://tldp.org/LDP/abs/html/arrays.html#SCRIPTARRAY

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜