Sye*_*Ali 1 shell-script text-processing
如何迭代以逗号分隔的文件?
我尝试了以下方法:
$ cat file | tr ',' '\n' > /tmp/f1
$ while read -r line;do
echo $line;
done < /tmp/f1
Run Code Online (Sandbox Code Playgroud)
如何在不创建临时文件的情况下迭代第一行内容?
有任何想法吗?
首先,避免使用 shell loops 进行文本解析。这很难做到,很容易出错,而且很难阅读。而且很慢。非常非常缓慢。相反,使用awk专门设计用于“字段”读取的类似内容。例如,使用此输入文件:
foo, bar, baz
oof, rab, zab
Run Code Online (Sandbox Code Playgroud)
您可以使用awk -F,将字段分隔符设置为,:
$ awk -F, '{ print "The 1st field is",$1,"the 2nd", $2,"and the 3rd", $3}' file
The 1st field is foo the 2nd bar and the 3rd baz
The 1st field is oof the 2nd rab and the 3rd zab
Run Code Online (Sandbox Code Playgroud)
即使您坚持在 shell 中执行此操作,您也不需要临时文件,也不需要tr. 你可以告诉while read用逗号分隔:
$ while IFS=, read -r one two three; do
echo "The 1st field is $one, the 2nd $two and the 3rd $three";
done < file
The 1st field is foo, the 2nd bar and the 3rd baz
The 1st field is oof, the 2nd rab and the 3rd zab
Run Code Online (Sandbox Code Playgroud)