在R语言中解压远程服务器上带密码的ZIP文件遇阻求助
Hey there! Let's break down why your script isn't working and fix it step by step. The biggest culprit here is spaces in your filename—shell commands treat spaces as argument separators, so Data Science Lifecycle.zip gets split into three separate inputs instead of one file. Here's how to resolve this, plus other key checks:
1. Wrap Filenames in Quotes to Handle Spaces
When building your system command, enclose the filename (and even the password, if it has special characters) in single quotes. This tells the shell to treat the entire string as a single entity. Update your command line like this:
sys_command = paste0("unzip -P '", pw, "' '", file, "'")
The single quotes around file ensure spaces in the filename don't break the command.
2. Fix the File Path (Critical for Remote Servers!)
You're using a Windows-style path (C:/Users/Username/Documents) but mentioned you're working on a remote server. Most remote servers run Linux/Unix, which uses forward-slash paths like /home/your_username/documents instead of Windows drive letters. Double-check that the path argument in list.files() points to the correct directory on your remote server, not your local machine.
3. Refine Your ZIP File Pattern
Your current pattern ".zip" will match any file with .zip anywhere in the name (like report.zip.backup). To only match files ending with .zip, use a proper regex pattern:
file_list <- list.files(path = "/home/your_username/documents", pattern = "\\.zip$", all.files = TRUE)
The \\. escapes the dot (since it's a special character in regex) and $ ensures we only match the end of the filename.
4. Verify Unzip is Installed on the Remote Server
Some Linux servers don't come with unzip pre-installed. Test this by running the following directly in your remote server's terminal:
unzip --version
If you get an error, install it using your server's package manager:
- For Ubuntu/Debian:
sudo apt install unzip - For CentOS/RHEL:
sudo yum install unzip
Full Modified Script
Here's the complete, fixed script with all the above adjustments:
# Update path to your remote server's actual directory file_list <- list.files(path = "/home/your_username/documents", pattern = "\\.zip$", all.files = TRUE) pw = readline(prompt = "Enter the password: ") for (file in file_list) { # Quoted password and filename to handle special characters/spaces sys_command = paste0("unzip -P '", pw, "' '", file, "'") system(sys_command) }
内容的提问来源于stack exchange,提问作者kchuying

