Skip to content
Advertisement

How to select a specific range of rows from a text file with bash script [closed]

I want to choose a range of rows, every 9 rows start a new range. In the next example new range start every 8 positions: Line 2, 10 and 18 are the tittle, Line 3, 11 and 19 are the comment, Line 4, 12 and 19 are the path…

I need to parametrize this for after insert in a DB:

Example:

Line1
Line2       [logs-app1]
Line3                comment = Logs
Line4                path = /data/logs/
Line5                valid users = "Access group1"
Line6                read only = yes
Line7                writable = no
Line8                browseable = no
Line9
Line10      [logs-app2]
Line11               comment = Logs
Line12               path = /data/logs/
Line13               valid users = "Access group2"
Line14               read only = yes
Line15               writable = no
Line16               browseable = no
Line17
Line18      [logs-app3]
Line19               comment = Logs
Line20               path = /data/logs/
Line21               valid users = "Access group3"
Line22               read only = yes
Line23               writable = no
Line24               browseable = no
Line25

How do I select a specific range of rows from a text file with bash script?


Thanks @glenn jackman for your help. My objective is to have all variables for after insert in a DB oracle ordinated Schema. What is the best way in order to do this?

get_range() {
    local -i i=$1
    local start=$((8*(i-1)+1)) end=$((8*i))
    sed -n "$start,$end p; $end q" file.txt
}

for i in $(seq 1 $END); do get_range ($i); done ?????


while
    read
    IFS=  read -r app
    IFS== read -r _ comment
    IFS== read -r _ path
    IFS== read -r _ users
    IFS== read -r _ read_only
    IFS== read -r _ writable
    IFS== read -r _ browsable
do
    echo "var1: $app"
    echo "var2: $comment"
    echo "var3: $path"
    echo "var4: $users"
    echo "var5: $read_only"
    echo "var6: $writable"
    echo "var7: $browsable"
done < file.txt

Advertisement

Answer

You could do this to get the nth range of lines:

$ get_range() {
    local -i i=$1
    local start=$((8*(i-1)+1)) end=$((8*i))
    sed -n "$start,$end p; $end q" file
}
$ get_range 2

[logs-app2]
         comment = Logs
         path = /data/logs/
         valid users = "Access group2"
         read only = yes
         writable = no
         browseable = no

while
    read
    IFS=  read -r app
    IFS== read -r _ comment
    IFS== read -r _ path
    IFS== read -r _ users
    IFS== read -r _ read_only
    IFS== read -r _ writable
    IFS== read -r _ browsable 
do
    echo "var1: $app"
    echo "var2: $comment"
    echo "var3: $path"
    echo "var4: $users"
    echo "var5: $read_only"
    echo "var6: $writable"
    echo "var7: $browsable" 
done < file
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement