简体   繁体   English

从bash脚本中的行号开始读取行

[英]Read lines starting from a line number in a bash script

I'm trying to read a file line by line starting from a specific line in bash. 我正在尝试从bash中的特定行开始逐行读取文件。 I have already used the while command to read each line of the file by incrementing the count. 我已经使用while命令通过递增计数来读取文件的每一行。 Can I make it start from a specific line? 我可以从特定的线开始吗?

let count=0
declare -a ARRAY

while read LINE; do
ARRAY[$count]=$LINE 
vech=${ARRAY[$count]}
    if [...blah ..]
     then
    ...blah..
    fi 
sleep 2 
((count++)) 
done < filec.c 

Any kind of help in the form of suggestions or algorithms are welcome. 欢迎以建议或算法的形式提供任何形式的帮助。

Edit: I'm trying to pass the line number as a variable . 编辑:我正在尝试将行号作为变量传递。 I am Grepping for a specific pattern and if found, should pass the line number starting from the pattern. 我正在Grepping一个特定的模式,如果找到,应该从模式开始传递行号。

I would use sed 's addresses to start at a particular line number and print to the end of the file: 我会使用sed地址从特定的行号开始并打印到文件的末尾:

lineNumber=10
sed -n "$lineNumber"',$p' |
while read line; do
  # do stuff
done

Either that or, as Fredrik suggested, use awk : 或者,正如Fredrik建议的那样,使用awk

lineNumber=10
awk "NR > $lineNumber" |
while read line; do
  # do stuff
done

What about something like this? 这样的事情怎么样?

while read -r line
do
    echo "$line"
done < <(tail -n +number file.name)

It's not POSIX compatible, but try on your Bash. 它不是POSIX兼容的,但试试你的Bash。 Of course, do what you want with $line inside while loop. 当然,在循环中用$ line做你想要的东西。
PS: Change number with yhe number line you want and file.name with the file name. PS:使用您想要的数字行更改数字,使用文件名更改file.name。

Some of the many ways: http://mywiki.wooledge.org/BashFAQ/011 其中一些方法有: http//mywiki.wooledge.org/BashFAQ/011

Personally: 亲身:

printf '%s\n' {1..6} | { mapfile -ts 3 x; declare -p x; }                  

Also, don't use all-caps variable names. 另外,不要使用全大写变量名。

Just keep a counter. 只要保持一个柜台。 To print all lines after a certain line, you can do like this: 要在某一行之后打印所有行,您可以这样做:

#!/bin/bash

cnt=0
while read LINE
do
    if [ "$cnt" -gt 5 ];
    then
        echo $LINE
    fi
    cnt=$((cnt+1))
done < lines.txt

or, why not use awk: 或者,为什么不使用awk:

awk 'NR>5' lines.txt 

Just go a read a certain number of lines up to the number you want and start your logic to read the rest. 只需读取一定数量的行,直到你想要的数字,并开始你的逻辑阅读其余的。

There is no way to economize on a "text" file, you can't skip lines without actually reading them. 没有办法节省“文本”文件,你不能跳过行而不实际读取它们。 The lines are delimited by 0x0a and of variable lengths. 这些行由0x0a和可变长度分隔。 Therefore each delimiter must be scanned and counted to reach a certain "line-number". 因此,必须扫描每个分隔符并计数以达到某个“行号”。 There are gimmicks that let you think you didn't read them, but you did. 有噱头可以让你觉得你没有读过它们,但是你做到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM