如何使用bash脚本从文本文件中选择特定范围的行

时间:2019-03-21 11:02:52

标签: linux bash

我想选择一个行范围,每9行开始一个新范围。在下一个示例中,新范围每8个位置开始:第2、10和18行是标题,第3、11和19行是注释,第4、12和19行是路径...

在插入数据库后,需要对此进行参数化:

示例:

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

如何使用bash脚本从文本文件中选择特定范围的行?


感谢@glenn jackman的帮助。我的目标是将所有变量插入数据库后的oracle Schema中。这样做的最佳方法是什么?

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

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作以获取第 n 行范围:

$ 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