我有两个文件。
~/directory1/7120599_S1.txt
hello world!
~/directory2/7120599_S7.txt
bye world!
我正在寻找将 7120599_S1.txt
的内容 append 到 7120599_S7.txt
末尾的 Perl 代码。以下命令适用于 Linux:
$ cat ~/directory1/7120599_S1.txt >> ~/directory2/7120599_S*.txt
新建~/directory2/7120599_S7.txt
hello world!
bye world!
但由于某些原因,这在 Perl 中不起作用
system "cat ~/directory1/7120599_S1.txt >> ~/directory2/7120599_S*.txt"
相反,它会在 directory2
中创建一个名为 7120599_S*.txt
的新文件。如何让 Perl 识别 Linux 通配符?
最佳答案
如果我们看一下 POSIX shell :
For the other redirection operators, the word that follows the redirection operator shall be subjected to tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal. Pathname expansion shall not be performed on the word by a non-interactive shell; an interactive shell may perform it, but shall do so only when the expansion would result in one word.
路径名扩展是指像 *.txt
这样的 glob。
Bash shell 并没有严格遵循 POSIX,而是试图更加方便和明智,包括即使在非交互模式下也将路径名扩展应用于重定向目标。通常,您的交互式 shell 将是 Bash。
但是,当您运行 system
命令时,这通常会运行一个更简单的符合 POSIX 标准的 shell(尽管这完全取决于您的操作系统)。通常这个 shell 安装为 /bin/sh
。
如果你想要 Bash,你必须明确地运行 Bash,例如
system "bash", "-c", "cat ~/directory1/7120599_S1.txt >> ~/directory2/7120599_S*.txt"
顺便说一下,如果您设置了 POSIXLY_CORRECT
环境变量,您可以强制 Bash 遵循 POSIX。
关于linux - 在 Perl 脚本中使用 Linux 通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898896/