如何使用 space/tab 遍历文件
How to loop over a file with space/tab
我有一个文件“sample.txt”看起来像:
apple 1
banana 10
并且我正在使用以下 shell 代码循环遍历以下行:
for line in $(cat sample.txt)
do
echo $(echo $line| cut -f1)
done
我的预期输出是
apple
banana
但我得到了:
apple
1
banana
10
我可以猜到 shell 将每一行作为一个列表。是否可以解决这个问题?
试试下面的代码:
while read line; do
echo "$line" | cut -d " " -f1
# ├────┘
# |
# └ Split at empty space
done <sample.txt
您可以使用 shell 内置 read
命令消除对 cut
实用程序的使用,如下所示:
#!/bin/bash
while read first rest
do
echo $first
done < sample.txt
输出:
apple
banana
关键在于如何使用read
命令。来自 bash
联机帮助页:
read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split into
words as described above under Word Splitting, and the first word is assigned to the first name, the second word to the second
name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the
last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values.
在我们的例子中,我们对第一个词感兴趣,它由 read
分配给 shell 变量 first
,而该行中的其余词是分配给 shell 变量 rest
。然后我们只输出 shell 变量的内容 first
以获得所需的输出。
我有一个文件“sample.txt”看起来像:
apple 1
banana 10
并且我正在使用以下 shell 代码循环遍历以下行:
for line in $(cat sample.txt)
do
echo $(echo $line| cut -f1)
done
我的预期输出是
apple
banana
但我得到了:
apple
1
banana
10
我可以猜到 shell 将每一行作为一个列表。是否可以解决这个问题?
试试下面的代码:
while read line; do
echo "$line" | cut -d " " -f1
# ├────┘
# |
# └ Split at empty space
done <sample.txt
您可以使用 shell 内置 read
命令消除对 cut
实用程序的使用,如下所示:
#!/bin/bash
while read first rest
do
echo $first
done < sample.txt
输出:
apple
banana
关键在于如何使用read
命令。来自 bash
联机帮助页:
read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split into
words as described above under Word Splitting, and the first word is assigned to the first name, the second word to the second
name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the
last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values.
在我们的例子中,我们对第一个词感兴趣,它由 read
分配给 shell 变量 first
,而该行中的其余词是分配给 shell 变量 rest
。然后我们只输出 shell 变量的内容 first
以获得所需的输出。