Shell 脚本从文件中单独读取列

Phi*_*rly 2 awk shell-script columns

当我们有一种类似列表的文件时:

Mary 34
George 45
John 56
Josh 29
Run Code Online (Sandbox Code Playgroud)

使用awk命令$1指的是第一列和$2第二列。但是一旦我们编写了一个shell脚本,我们就可以使用read line读取整行或者我们可以使用read number读取第一个单词,对吗?所以我的问题是在上面如果我想阅读第二列,如果不使用awkshell 脚本中的命令,我将如何做到这一点。

Oli*_*lac 6

while read firstcol secondcolandtherest ;
do
    something
done < the_file
Run Code Online (Sandbox Code Playgroud)

即:当您将多个参数放入“读取”时,它会将第一个参数放在第一个参数中,将第二个参数放在第二个参数中,依此类推。在最后一个参数中,它会将“行的其余部分”放入。

一些例子:

#if you want to read line by line: only 1 arg (therefore, it puts everyuthing in it, as the only arg is the last arg)
while read whole_line ; 
do
     something with "$whole_line"
done

#if you only want only column 1 in $first, and everything else in $second_and_rest_of_line:
while read  first second_and_rest_of_line
 do
     something with "$first" and "$second_and_rest_of_line"
done

#if you only want col 1 and 2, and don't care about any extra cols:
while read  first  second  nonimportant
do
     something with $first and "$second" #and we don't care about $nonimportant's content
done
Run Code Online (Sandbox Code Playgroud)

请注意:您应该真正添加“-r”(获取原始输入)选项来读取,并根据您的需要修改 IFS ......但上面的例子是为了讨论“参数”,而不是正确的读取调用。请参阅http://mywiki.wooledge.org/BashPitfalls了解有关此和许多其他细微之处的信息