我有一个看起来像这样的文件:
work:week:day:england:
work1:week:day:sweden:
work2:week:day::
.....
每次我循环遍历列表时,我都希望将每个字符串作为我可以使用的变量。 例如,如果我想知道我在哪个位置工作,我将从第一列“工作*”中获取第四个位置列
我试过这个:
for country in $( awk -F '[:]' '{print $1}' file.txt); do
if [[ "$country" == "england" ]];
then
echo "This user works in England!"
else
echo "You do not work in England!"
fi
done
我想让每个字符串用冒号分隔,作为每个循环的每一行的变量。
最佳答案
为此您可以只使用 bash:将 IFS
(内部字段分隔符)设置为 :
,这将正确捕获字段:
while IFS=":" read -r a b c country
do
echo "$country"
done < "file"
返回:
england sweden
This way you will be able to use $a
for the first field, $b
for the second, $c
for the third and $country
for the forth. Of course, adapt the number and names to your requirements.
All together:
while IFS=":" read a b c country
do
if [[ "$country" == "england" ]]; then
echo "this user works in England"
else
echo "You do not work in England"
fi
done < "file"
关于bash - 使用冒号分隔的字符串遍历文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994461/