3

I want to do text processing for lines in file.txt that ends with 0, I wrote an easy form of it to ask my question clearly.

$ cat file.txt
1 343 4352 0
324 4324 4324 324
432 432 2345 0

$ cat script.sh
for i in `grep " 0$" file.txt`
do
  echo $i; 
done

I want the output to be:

1 343 4352 0

432 432 2345 0

I want $i variable to be "1 343 4352 0" and after that to be "432 432 2345 0" but in this script $i variable is valued 1 then 343

2
  • as per @AvinashRaj comment, there is no loop required here Commented Jul 6, 2015 at 9:13
  • thanks , but my script isn't this. this is the easy for of it to make my question clear, I need i variable to be the out put of grep to do sth with them. and also I want to learn how to do this with for. Commented Jul 6, 2015 at 9:16

3 Answers 3

2

You can do this:

IFS=$'\n' arr=($(grep ' 0$' file.txt))
for  i in "${arr[@]}"
do
  echo "$i"
  #do other tasks here.
done
Sign up to request clarification or add additional context in comments.

1 Comment

Fair enough, I posted an alternative then with the caveat it's also probably not what the OP really should be doing at all.
2

This is almost certainly NOT the right way to do whatever it is you are trying to do but to answer the specific question you asked:

$ grep ' 0$' file |
while IFS= read -r i
do
    echo "$i"
done
1 343 4352 0
432 432 2345 0

If you are going to be doing text processing - do it in awk, not shell for simplicity, clarity, robusteness, performance, and every other desirable attribute of good software:

$ awk '/ 0$/ {i=$0; print i}' file
1 343 4352 0
432 432 2345 0

The above is just setting/using a variable to show how to do that.

Comments

0

Use the Bash built-in "REPLY"

#!/bin/bash
while read -r ;do
    echo $REPLY ;done < file.txt

cheers Karim

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.