我想知道如何在bash脚本中从第二行到文件末尾读取csv
文件的每一行。
我知道如何在bash中读取文件:
while read line
do
echo -e "$line\n"
done < file.csv
但是,我想读取从第二行开始到文件末尾的文件。我怎样才能做到这一点?
答案 0 :(得分:47)
tail -n +2 file.csv
来自man page:
-n, --lines=N
output the last N lines, instead of the last 10
...
If the first character of N (the number of bytes or lines) is a '+',
print beginning with the Nth item from the start of each file, other-
wise, print the last N items in the file.
在英语中,这意味着:
tail -n 100
打印最后100行
tail -n +100
打印从第100行开始的所有行
答案 1 :(得分:13)
使用sed
的简单解决方案:
sed -n '2,$p' <thefile
其中2
是您想要读取的行数。
答案 2 :(得分:7)
或者(纯粹的bash )......
{ for ((i=1;i--;));do read;done;while read line;do echo $line;done } < file.csv
写得更好:
linesToSkip=1
{
for ((i=$linesToSkip;i--;)) ;do
read
done
while read line ;do
echo $line
done
} < file.csv
这项工作即使是linesToSkip == 0或linesToSkip&gt; file.csv的行数
修改强>:
为()
更改{}
,因为gniourf_gniourf要求我考虑:首先语法生成子shell ,而{}
没有。
当然,对于仅跳过一行(作为原始问题的标题),循环for (i=1;i--;));do read;done
可以简单地替换为read
:
{ read;while read line;do echo $line;done } < file.csv
答案 3 :(得分:6)
有很多解决方案。我最喜欢的一个是:
(head -2 > /dev/null; whatever_you_want_to_do) < file.txt
您也可以使用tail
跳过所需的行:
tail -n +2 file.txt | whatever_you_want_to_do
答案 4 :(得分:6)
取决于你想对你的线做什么:如果你想将每个选定的线存储在一个数组中,最好的选择绝对是内置mapfile
:
numberoflinestoskip=1
mapfile -s $numberoflinestoskip -t linesarray < file
将从第2行开始,在数组file
中存储文件linesarray
的每一行。
help mapfile
了解更多信息。
如果您不想将每一行存储在数组中,那么还有其他非常好的答案。
正如F. Hauri在评论中建议的那样,只有在你需要将整个文件存储在内存中时才适用。
否则,你最好的选择是:
{
read; # Just a scratch read to get rid (pun!) of the first line
while read line; do
echo "$line"
done
} < file.csv
注意:没有涉及/需要的子shell。
答案 5 :(得分:1)
我会得到一个变量。
#!/bin/bash
i=0
while read line
do
if [ $i != 0 ]; then
echo -e $line
fi
i=$i+1
done < "file.csv"
UPDATE 上面将检查csv每行的$i
变量。因此,如果您拥有数百万行的非常大的csv文件,它将占用大量的CPU周期,对大自然没有好处。
使用sed
可以使用一个衬管删除第一行CSV文件,然后将剩余文件输出到while
循环。
sed 1d file.csv | while read d; do echo $d; done
答案 6 :(得分:1)
这将有效
i=1
while read line
do
test $i -eq 1 && ((i=i+1)) && continue
echo -e "$line\n"
done < file.csv