假设我有这样的数据:
1.1G file1
2.2G file2
3.3G file3
这样做的时候:
1.1G
file1
2.2G
file2
3.3G
file3
我想要它做什么:
1.1G file1
(Loops)
2.2G file2
(Loops)
3.3G file3
这是我的代码:
cd /home/users
hdSize=$(du -h --max-depth=1 | awk '{print $1,$2}' | awk '$1~/G/' | sed '$d')
for sizeAlert in $hdSize
do
gbSize=$(echo $sizeAlert | awk ‘{print $1}’ | tr -d “G”)
#fileName=$(du -h —-max-depth=1 | awk ‘{print $2} | tr -d “./“)
echo $gbSize
done
答案 0 :(得分:0)
您的脚本无法正常工作的原因是,bash for
循环在找到空格,制表符或换行符之类的空白时会拆分。
因此循环中的每个项目都将是:
1.1G
file1
2.2G
file2
...
因此,当您执行echo $sizeAlert | awk '{print $1}' | tr -d "G"
时,对1.1G
有意义,而对file1
则没有任何意义。
您可以设置IFS
(内部字段分隔符)
IFS=$'\n'
for sizeAlert in $hdSize
do
fileName=$(echo $sizeAlert | awk '{print $2}' | tr -d "./")
gbSize=$(echo $sizeAlert | awk '{print $1}' | tr -d "G")
echo $gbSize $fileName
done
或者您可以在read
循环中使用while
while read gbSize fileName
do
fileName=$(echo $fileName | tr -d "./")
gbSize=$(echo $gbSize | tr -d "G")
echo $gbSize $fileName
done <<< $hdSize
无论如何,this(已在评论中提到)将是满足您需求的更有效解决方案