Reputation: 63
i want to read a file and print it on the screen by shell scripting , so i have find a simple code to do this :
#! /bin/bash
FILENAME=$1
Lines=$(wc -l < $FILENAME)
count=0
while [ $count -lt $Lines ]
do
let count++
LINE= `head -n $count $FILENAME | tail -1 `
echo "$count $LINE"
done
echo -e "\nTotal $count lines read"
, but i'm didn't understand the following line :
LINE= `head -n $count $FILENAME | tail -1 `
any help ??
Upvotes: 1
Views: 237
Reputation: 9
the following simple script will help
file=$1
cat $file | while read line
do
echo $line
done
Reading file into an array,
file=$1
let index=1
while IFS=$'\n' read -r -a myArray
do
file_content_array[$index]="${myArray[0]}"
echo ${file_content_array[$index]}
let index=$index+1
done < $file
Upvotes: 0
Reputation: 246744
Very inefficient as others have pointed out. @devnull's observation cat -n file
is spot on.
To emulate that in bash, I'd write:
declare -i linenum=0
while IFS= read -r line; do
printf "%8d %s\n" $((linenum++)) "$line"
done < file
Upvotes: 1
Reputation: 123448
The line
LINE= `head -n $count $FILENAME | tail -1 `
doesn't do what you think it should. It tries to execute the command produced by the output of
head -n $count $FILENAME | tail -1
with a variable LINE
(without a value) passed to it.
Instead say:
LINE=$(head -n $count $FILENAME | tail -1)
which would essentially give the line number count
in the file.
As an alternate, you could say:
LINE=$(sed -n ${count}'p' $FILENAME)
to get the line.
Your script seems to be emulating
cat -n filename
Upvotes: 1
Reputation: 7803
This will first run head
on the file, taking the first $count
lines of the file. It is then piped (|
) into tail, which (due to the -1
) will return only the last line of the output of head (i.e. the count
th line).
This will then get assigned to the LINE
variable for processing
It's worth noting that this approach will work, but it is very inefficient.
Upvotes: 1