LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shell programming (https://www.linuxquestions.org/questions/linux-newbie-8/shell-programming-470945/)

pawarsac 08-05-2006 01:30 AM

Shell programming
 
Hello
I want to read one file line by line by my shell script
(Just like reading file in C by fopen and then getch/gets).
After reading it i want to delete that line.
How I can achive this and using which utility?

sac

Tinkster 08-05-2006 01:36 AM

Doesn't make too much sense to me ... what's the background of this?
You could just read all lines and then delete the whole file? :)


Cheers,
Tink

konsolebox 08-05-2006 02:11 AM

here's some concepts
Code:

cat file > tmp
IFS=$'\n'
for a in $(<tmp); do
    # remove the line
    sed -i -n 1\!p file
    # OR sed -i -n /"$a"/\!p file
done


spirit receiver 08-05-2006 04:20 AM

I understand that you want to process each line somehow and have the line removed when you're done with it?
So,
Code:

#! /bin/bash

FILENAME=your_file

while [[ -s "$FILENAME" ]]
do
  read < "$FILENAME"
  sed -i '1d' "$FILENAME"
  echo "$REPLY processed and deleted."
done

To me, this only seems to make sense if other processes may append lines to the file, and in that case you'll need some file locking (in both the reading and writing processes). Have a look at
Code:

#! /bin/bash

FILENAME=your_file

while [[ -s "$FILENAME" ]]
do
  LINE=$( flock "$FILENAME" \
          bash -c "read <'$FILENAME';\
                  sed -i 1d '$FILENAME';\
                  echo \"\$REPLY\"" )
  echo "$LINE processed and deleted."
done


theYinYeti 08-05-2006 04:43 AM

This can be as simple as:
Code:

while read line <file; do process $line; sed -i '1 d' file; done
Yves.


All times are GMT -5. The time now is 04:15 AM.