bash 使用 shell 脚本读取文本文件中特定行中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16270970/
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
Read words in a specific line in a text file using shell script
提问by user2330632
In my Bash shell script, I would like to read a specific line from a file; that is delimited by :and assign each section to a variable for processing later.
在我的 Bash shell 脚本中,我想从文件中读取特定行;由分隔:并将每个部分分配给一个变量以供稍后处理。
For example I want to read the words found on line 2. The text file:
例如,我想阅读第 2 行中的单词。文本文件:
abc:01APR91:1:50
Jim:02DEC99:2:3
banana:today:three:0
Once I have "read" line 2, I should be able to echo the values as something like this:
一旦我“阅读”了第 2 行,我应该能够像这样回显这些值:
echo "$name";
echo "$date";
echo "$number";
echo "$age";
The output would be:
输出将是:
Jim
02DEC99
2
3
回答by Jonathan Leffler
For echoing a single line of a file, I quite like sed:
对于回显文件的单行,我非常喜欢sed:
$ IFS=: read name date number age < <(sed -n 2p data)
$ echo $name
Jim
$ echo $date
02DEC99
$ echo $number
2
$ echo $age
3
$
This uses process substitutionto get the output of sedto the readcommand. The sedcommand uses the -noption so it does not print each line (as it does by default); the 2pmeans 'when it is line 2, print the line'; datais simply the name of the file.
它使用进程替换得到的输出sed到read命令。该sed命令使用该-n选项,因此它不会打印每一行(默认情况下);的2p装置“时,它是第2行,打印线”; data只是文件的名称。
回答by anubhava
You can use this:
你可以使用这个:
read name date number age <<< $(awk -F: 'NR==2{printf("%s %s %s %s\n", , , , )}' inFile)
echo "$name"
echo "$date"
echo "$number"
echo "$age"

