我想知道如何csv在bash脚本中从第二行到文件末尾读取文件的每一行.
我知道如何在bash中读取文件:
while read line
do
echo -e "$line\n"
done < file.csv
Run Code Online (Sandbox Code Playgroud)
但是,我想读取从第二行开始到文件末尾的文件.我怎样才能做到这一点?
Mar*_*tin 54
tail -n +2 file.csv
Run Code Online (Sandbox Code Playgroud)
从手册页:
-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.
Run Code Online (Sandbox Code Playgroud)
在英语中,这意味着:
tail -n 100 打印最后100行
tail -n +100 打印从第100行开始的所有行
fge*_*fge 16
简单解决方案sed:
sed -n '2,$p' <thefile
Run Code Online (Sandbox Code Playgroud)
2您想要读取的行数在哪里.
否则(纯粹的bash)......
{ for ((i=1;i--;));do read;done;while read line;do echo $line;done } < file.csv
Run Code Online (Sandbox Code Playgroud)
写得好:
linesToSkip=1
{
for ((i=$linesToSkip;i--;)) ;do
read
done
while read line ;do
echo $line
done
} < file.csv
Run Code Online (Sandbox Code Playgroud)
即使linesToSkip == 0或linesToSkip> file.csv的行数,这项工作也是如此
编辑:
改为()为{}gniourf_gniourf命令我考虑:第一种语法生成一个子shell,而whille {}却没有.
当然,对于仅跳过一行(作为原始问题的标题),循环for (i=1;i--;));do read;done可以简单地替换为read:
{ read;while read line;do echo $line;done } < file.csv
Run Code Online (Sandbox Code Playgroud)
有很多解决方案.我最喜欢的一个是:
(head -2 > /dev/null; whatever_you_want_to_do) < file.txt
Run Code Online (Sandbox Code Playgroud)
您还可以使用tail跳过所需的行:
tail -n +2 file.txt | whatever_you_want_to_do
Run Code Online (Sandbox Code Playgroud)
取决于你想对你的线做什么:如果你想将每个选定的线存储在一个数组中,最好的选择绝对是内置的mapfile:
numberoflinestoskip=1
mapfile -s $numberoflinestoskip -t linesarray < file
Run Code Online (Sandbox Code Playgroud)
file将从第2行开始,在数组中存储每行文件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
Run Code Online (Sandbox Code Playgroud)
注意:没有涉及/需要的子shell.