0

in my script i need to loop through lines in a file, once i find some specific line i need to save it to variable so later on i can use it outside the loop, i tried the following but it wont' work:

count=0
res=""
python my.py -p 12345 |
  while IFS= read -r line
  do
     count=$((count+1))
     if [ "$count" -eq 5 ]; then
        res=`echo "$line" | xargs`
     fi
  done
echo "$res" 

it output nothing, i also tried this,

res=""

... in the loop...
   res=$res`echo "$line" | xargs`

still nothing. please help. thanks.

Update: Thanks for all the help. here is my final code: res=python my.py -p 12345 | sed -n '5p' | xargs

3
  • 1
    What exactly do you believe that line of code does? Commented Feb 27, 2015 at 22:16
  • 1
    var=$(sed -ne '5p' file) maybe? Commented Feb 27, 2015 at 22:21
  • @anubhava: the input is an command output. updated in the post Commented Feb 27, 2015 at 22:38

1 Answer 1

1

for finding a specific line in a file, have you considered using grep?

grep "thing I'm looking for" /path/to/my.file

this will output the lines that match the thing you're looking for. Moreover this can be piped to xargs as in your question.

If you need to look at a particularly numbered line of a file, consider using the head and tail commands (which can also be piped to grep).

cat /path/to/my.file | head -n5 | tail -n1 | grep "thing I'm looking for"

These commands take the first lines specified (in this case, 5 and 1 respectively) and only prints those out. Hopefully this will help you accomplish your task.

Happy coding! Leave a comment if you have any questions.

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

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.