• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to read each line from file in Shell script

 
Moniphal Say
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

I'm not familar with Linux, and shell script.
I want to read line from a file, is there any command to do that?



I want to read each line (1 line at the time) of this text and print it to std output or assign to any variable.
I've checked with command : but with that I can only print out the first n line of the n line at the end of file.

I would appreciate your help
Regards,
Moniphal
 
Mark Wuest
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<blockquote>


I want to read each line (1 line at the time) of this text and print it to std output or assign to any variable.
I've checked with command : but with that I can only print out the first n line of the n line at the end of file.

</blockquote>
(Noticed more than one line)

I believe you want the xargs command... Try doing a "man xargs" and see...

Mark
[ August 08, 2005: Message edited by: Mark Wuest ]
 
Rick Beaver
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cat <file>

Will print out every line of a file to stdout

If you want to do stuff with each line you need to loop - in your shell, or a script, like this:

for i in `cat file`
do
#do your stuff to the line which is $i
done

Or in bash you can do it like:

for i in $(cat file)
do
#do your stuff to $i here
done

Hope this helps.
 
Mark Wuest
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(Need a break from Real Work... )

will execute command once for each line in file.txt, passing the contents of that line as arguments to command. Command could be "echo" to just spit the lines back out, or "set" to set a variable to the contents of that line.

If each line only has one word, then the for i in `cat` thing will work and is more intuitive. If any line has more than one word, each word in that line will be an interation through the loop. I.e.:


...back to my Regularly Scheduled Programming...

Mark
[ August 09, 2005: Message edited by: Mark Wuest ]
 
Craig Jackson
Ranch Hand
Posts: 405
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another alternative is to use awk. Awk is something I am not completely familiar with, but it can do some good things, if you take the time to learn it:





or


 
Moniphal Say
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

Thanks so much for your solution.I've got it now.

Regards,
Moniphal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic