0
cat test.txt
#this is comment
line 1
line 2
#this is comment at line 3
line4

script:

result=`awk '/^#.*/ { print }' test.txt `

for x in $result
do
echo x
done

expected output:

#this is comment
#this is comment at line 3

getting output:

#this
is
comment
#this
is
comment
at
line
3

but when i execute this command awk '/^#.*/ { print }' test.txt, i get expected result. I am putting this in loop because I need to capture each comment one at a time, not all together.

2 Answers 2

2

This happens because for x in $result will loop through each word in $result - that's what for is meant to do.

Try this instead:

echo "$result" | while read x; do
    echo "$x"
done

read will take one line at a time, which is what you need here.

Sign up to request clarification or add additional context in comments.

1 Comment

With bash, you can use a here-string: while read line; ...; done <<< "$result". Using a pipeline puts the while loop in a subshell that may have undesirable side-effects.
2

Your issue is not the awk part, but is the for part. When you do

for x in yes no maybe why not
do
   echo x
done

You'll get

yes
no
maybe
why
not

That is, the list that for is looping over is automatically space-delimited.

One fix, I suppose, is to wrap the comments in quotes; then for will treat each quoted comment as a single item. legoscia's fix (using read in a while loop) seems even better to me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.