bash While 循环,如何从文本文件的第二行读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8333880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
While loop, how to read from second line of text file
提问by LatinUnit
i've tried everything for the past 2 hours to get this working but my experience in shell and programming is limited.
在过去的 2 个小时里,我已经尝试了一切来让这个工作正常进行,但我在 shell 和编程方面的经验有限。
I have a loop
我有一个循环
while IFS="," read var1 var2 var3 var4 var5 ; do
statements here...
done < $file
Now the operation inside statement is to read from a text file that has 5 fields as you can see and then use them to create accounts in Linux using bash
现在,inside 语句的操作是从一个文本文件中读取,如您所见,该文件有 5 个字段,然后使用它们在 Linux 中使用 bash 创建帐户
useradd $var1 -p var2 -g var3and so on
useradd $var1 -p var2 -g var3等等
I want to make the script to start reading from the second line only, i cant get it working. something like while ifs=, read (from second line) var 1 var 2 var3 etc.
我想让脚本只从第二行开始阅读,我无法让它工作。类似于 while ifs=, read (from second line) var 1 var 2 var3 等。
the reason for this is that the file is an exported database from excel to csv so the first line would contain titles like first name dob enrolled etc etc and is not needed
这样做的原因是该文件是从 excel 到 csv 的导出数据库,因此第一行将包含诸如名字 dob 注册等的标题,并且不需要
Your help is appreciated
感谢您的帮助
Addition:
添加:
Before the users are being created, I have added an if statement and if users meet a condition then they will be created.
在创建用户之前,我添加了一个 if 语句,如果用户满足条件,则将创建它们。
if [ "$var5" == "fullyenrolled" ]; then
continue with account creation...
echo "$var1 successfuly created"
else
echo "Sorry user $var1 is not fully enrolled"
fi
the output of the echo is something like
回声的输出类似于
Full name is not fully enrolled
user1 successfuly created
user2 successfuly created
even if i add sed 1d | while IFS= etc etc. it seems that it is still reading the first line this is why im getting the first output like "full name is not fully enrolled"
即使我添加 sed 1d | 而 IFS= 等,它似乎仍在读取第一行,这就是为什么我得到第一个输出,如“全名未完全注册”
回答by Elias Dorneles
Use sed to "delete" the first line from the input passed to the while loop
使用 sed 从传递给 while 循环的输入中“删除”第一行
sed 1d $file | while ...
do
your statements here
done
回答by nyuszika7h
A solution using awk:
使用的解决方案awk:
awk 'NR >= 2 { print }' < "$file"

