我有一個檔案“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 將每一行作為一個串列。有可能解決這個問題嗎?
uj5u.com熱心網友回復:
試試下面的代碼:
while read line; do
echo "$line" | cut -d " " -f1
# ├────┘
# |
# └ Split at empty space
done <sample.txt
uj5u.com熱心網友回復:
cut您可以使用 shell 內置命令消除該實用程式的使用read,如下所示:
#!/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即可獲得所需的輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440881.html
標籤:贝壳
