user558134
user558134

Reputation: 1129

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!

Upvotes: 1

Views: 1128

Answers (3)

spdaley
spdaley

Reputation: 821

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.

Upvotes: 1

sjngm
sjngm

Reputation: 12861

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

Upvotes: 0

zwol
zwol

Reputation: 140589

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

Upvotes: 3

Related Questions