简体   繁体   English

Bash脚本来gzip特定文件扩展名

[英]Bash script to gzip specific file extensions

I was given a script that finds all html files and compresses them individually to a new location 给我一个脚本,该脚本可以找到所有html文件并将其分别压缩到新位置

#!/bin/bash
for i in .html; do
gzip < $i > /backup/full/$i
done

I'm not sure I fully understand how it works though, as it only functions if it is located in the same directory as the files. 我不确定我是否完全理解它的工作原理,因为它仅在与文件位于同一目录时才起作用。 What if for whatever reason the script is located elsewhere? 如果脚本出于任何原因而位于其他位置怎么办?

Trying something like this to add the file path results in both original and destination paths to be combined and an error 尝试这样添加文件路径会导致原始路径和目标路径都被合并,并且会出现错误

for i in /html/directory/*.html; do
gzip < $i > /backup/full/$i
done

Thank you for your time 感谢您的时间

You need to remove the original directory prefix when constructing the output filename. 构造输出文件名时,需要删除原始目录前缀。

gzip < "$i" > /backup/full/"$(basename "$i").gz"

or using a parameter expansion operator: 或使用参数扩展运算符:

gzip < "$i" > /backup/full/"${i##*/}".gz

Don't forget to quote your variables, so that filenames with whitespace will be processed properly. 不要忘了用引号将变量引起来,这样带有空格的文件名将被正确处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM