line-by-line processing : Linux Bash

Often we require to process a file content line by line. Linux inherently supports this thorough its powerful shell commands. Lets walk through some of the ways to parse a file line-by-line.



First, we can parse a file by catting a file and piping the file output to a while read loop.
The following bash script produces it own code as output. Isn't it interesting?

code for dumping own file content

#!bin/bash

cat $0 | while read line
do
echo $line;
done

Secondly, using file descriptors we can play a lot with it. But, before we will learn about firl descriptors in brief.


Under unix/linux OS, files are referenced, copied, and moved by unique numbers known as file descriptors.

0 stdinIt is(devie) usually the keyboard or mouse from where the input comes.
1stdoutIt is where output is redirected e.g. screen or file
2stderrIt is where the standard error messages are routed by commands, programs, and scripts.
$ some_command 2>&1

this means, the command sends all of the error messages to the same output device that the standard output goes to, which is normally the terminal.

Now, we will use this file descriptors to write the same shell script we wrote before.( which outputs its own code)


#!bin/bash

exec 3<&0  #redirect standard input to file descritpor 3

exec 0<$0 # redirect current file content to standard input

while read LINE   # simply read from standard input now
do 
echo $LINE;
done

exec 0<&3  # revert back stanrd input from 3 to 0

No comments:

Post a Comment