How find the number of lines in a file shell scripting and also take the lines from the file

part 1. But first if you like this sort of stuff https://discord.gg/4yYVkU4 join my coding group discord server
road map:

# This is a road map, it is recommended that you understand this so read on
#!/bin/bash
# part 1
LEN1=$( wc -l file.txt )
for i in $(seq 1 ${#LEN1})
do
    if [[ "${LEN1:i-1:1}" = " " ]]
    then
        POS="$i"
        break
    fi
done
LINECOUNT=$(( "${LEN1:0:POS}" ))

# part 2
for C in $(seq 1 $LINECOUNT)
do
    LINE1=$(head -$C file.txt | tail -1)
done
#!/bin/bash
# find the location of the space in a string
LEN1=$( wc -l file.txt )
for i in $(seq 1 ${#LEN1})
do
    if [[ "${LEN1:i-1:1}" = " " ]]
    then
        POS="$i"
        break
    fi
done
LINECOUNT=$(( "${LEN1:0:POS}" ))

The first part, LEN1 is being assigned to a string. The string is generated by the command $( wc -l file.txt ). wc is a command for finding stats on a document, the -l command returns a string formatted like this “12 file.txt” (” #oflines file.txt”). The for loop creates the variable i which iterates through the list created by “$(seq 1 ${#LEN1})”.
NOTE:$(seq 1 5)=1 2 3 4 5
${#} is used to get the length of a string, put the variable name after the #.
$( seq start end ) builds a list which has every number between start and end.

The next part is the if loop. The string I stated earlier has one thing that is crucial to separating the numbers from the letters. It has a space separating them. So the if statement takes a list slice from the string LEN1

${LEN1:i-1:1} is hard to explain but in simple terms means take a character from LEN1 starting from i-1. In python it would look like LEN1[i-1]

The complex explanation is this–start at i-1 and end at i-1+1 or ${LEN1:start:start+end}
This slice is then being compared to the string ” ” (space). If the string is equal to space the loop marks the position of the counter i and breaks out of the for loop

part 2

for C in $(seq 1 $LINECOUNT)
do
    LINE1=$(head -$C file.txt | tail -1)
    echo $LINE1
done

The for loop this time builds a list with the command seq which spans from 1 to the int LINECOUNT
head -$C file.txt this command means read lines 0-C
Say file.txt was this

Hello
welcome
to
my
coding
website

head -1 means take lines 0-1. You would get the value “Hello” returned.
head -2 means take lines 0-2. You would get “Hello” and “welcome”
To fix this “|” is added which pipes the output of “head -2 file.txt” to “tail -1”
tail -1 always takes the bottom most line.
head -3 file.txt | tail -1 means take lines (0-3)-(-1). You would only get “to” back.

If you join my server within 1 week from today I will give you the role “more than likely a person”

Leave a Reply

Your email address will not be published. Required fields are marked *