我正在编写一个脚本并想要运行BZIP2,但仅获得压缩比,压缩大小和未压缩的大小。
运行bzip2 filename
时,我得到:
test.txt: 5.769:1, 1.387 bits/byte, 82.67% saved, 48108 in, 8339 out.
我只想获得最后三个字段:
82.67% saved, 48108 in, 8339 out
我尝试了使用
的尴尬 bzip2 -v test.txt | awk '{print $1 $2 $3}'
以及
bzip2 -v test.txt | awk -F', ' '{print $1}'
,但由于它的字符串和定界符的间距不均匀,所以我不知道该怎么做。我也想摆脱任何文本,只输出数字,像这样 82.67% 48108 8339
我必须保持尽可能简单。谢谢!
编辑:
bzip2 -v test.txt | cat -A
的输出:
test.txt: 0.788:1, 10.154 bits/byte, -26.92% saved, 52 in, 66 out.
脚本:
#!/bin/sh
# program2.sh
#Name of the file input
NAME=$1
#Uncompressed size of the file input
UNCOMPRESSED=$(du -h $NAME | awk '{print $1}')
#################################################
#Prompts name entry if no argument provided, or stores given argument as name
if [ $# -eq 0 ];
then
echo "Error: No file name provided. Please run the script with a filename argument."
echo ""
exit
fi
echo ""
echo "$NAME will be compressed using the gzip, bzip2, and zip commands."
echo ""
echo "gzip:"
#echoUncompressed:t $UNCOMPRESSED"
gzip $NAME
gzip -l ${NAME%}.gz | awk ' NR == 2 {print "Uncompressed:t " $2} NR == 2 {print "Compressed:t " $1} NR == 2 {print "Ratio:tt " $3}'
gunzip ${NAME%}.gz
echo ""
echo "bzip2:"
echo "Uncompressed:t $UNCOMPRESSED"
#Run bzip2
bzip2 -v $NAME |& awk -F ',[[:blank:]]*' '{sub(/.$/, ""); printf "Ratio: %s, Uncompressed: %s, Compressed: %sn", $(NF-2), $(NF-1), $NF}'
bunzip2 ${NAME%}.bz2
echo ""
echo "zip:"
#echoUncompressed:t $UNCOMPRESSED"
#Run zip
zip -q ${NAME%.*}.zip $NAME
ZNAME="${NAME%.*}.zip"
unzip -ov $ZNAME | awk ' NR == 4 {print "Compressed:t " $3} NR == 4 {print "Ratio:tt " $4}'
您可以使用:
bzip2 -v test.txt |& awk -F ',[[:blank:]]*' '{sub(/.$/, "");
printf "Ratio: %s, Uncompressed: %s, Compressed: %sn", $(NF-2), $(NF-1), $NF}'
Ratio: 82.67% saved, Uncompressed: 48108 in, Compressed: 8339 out
在这里 -F ',[[:blank:]]*'
进行逗号,然后是0或更多的空格作为awk
的输入场分离器。
工作脚本演示
遵循简单的awk
可能会在同一方面帮助您:
your command |& awk '{sub(/.*byte, +/,"");print}'
按照Anubhava Sir'e建议编辑!&
现在也回答。
bzip2 -v Input_file |& awk '{sub(/.*byte, +/,"");split($0,a," ");print "Ratio: ",a[1],",Uncompressed: ",a[2]," Compressed:",a[3]}'
因此,当不使用脚本时,解决方案上述工作。但是,在A脚本中,从Stderr重定向到Stdout是不同的:
bzip2 -v $NAME 2>&1| awk -F ',[[:blank:]]*' '{sub(/.$/, ""); printf "Ratio: %s, Uncompressed: %s, Compressed: %sn", $(NF-2), $(NF-1), $NF}'
使用 2>&1
重定向在脚本中,在脚本中,您只需在其他解决方案中使用 command |& ...."