'How to loop over a file with space/tab
I have a file "sample.txt" looks like:
apple 1
banana 10
and I'm using the following shell code to loop over lines like:
for line in $(cat sample.txt)
do
echo $(echo $line| cut -f1)
done
My expected output is
apple
banana
But I got:
apple
1
banana
10
I can guess that shell takes each line as a list. Is it possible to remedy this?
Solution 1:[1]
Try the following code:
while read line; do
echo "$line" | cut -d " " -f1
# ??????
# |
# ? Split at empty space
done <sample.txt
Solution 2:[2]
You can eliminate the use of the cut utility by using the shell builtin read command as shown below:
#!/bin/bash
while read first rest
do
echo $first
done < sample.txt
which outputs:
apple
banana
The key is in how the read command is used. From the bash manpage:
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.
In our case, we are interested in the first word, which is assigned by read to the shell variable first, while the rest of the words in the line are assigned to the shell variable rest. We then just output the contents of the shell variable first to get the desired output.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siddharth Dushantha |
| Solution 2 | fpmurphy |
