2011年8月2日 星期二

Handling multiple lines in shell script

Shell script is good to work with ASCII line contents. When considering multiple lines, it needs some techniques.
1. Use pipe and read
cat A_File_With_Lines.txt | {
while :; do
read line
work_with line
if [ line_condition_end ]; then
break
fi
done
}
** NITES **
Two issues :
a. line_condition_end is very very very important because the "EOF" read will cause the shell to exit running.
b. The variables inside the | { } scope can't be used outside the braces

2. Use for loop
for line_in_file in $(cat A_File_With_Lines.txt); do
work_with line
done
** NITES **
a. This method requires the "lines in the file" do not contain any white space, tab, and other special words which can't be directly processed in script.
b. Because of a, this method is specially good for handling "files list which generated by ls or find"

沒有留言: