xargs 变量上的替换返回空字符串



我需要在目录树中搜索XML文件,并在另一个目录(staging_ojs_pootle(上为它们创建链接,用文件路径命名这些链接(替换每个点的斜杠(。

bash 命令不起作用,我卡在替换部分。 似乎 xargs 中名为"file"的变量在替换代码中无法访问(${file///.})

find directory/ -name '*.xml' | xargs  -I 'file' echo "ln" file staging_ojs_pootle/${file///.}

${} 结果中的替换给了我一个空字符串。

尝试使用 sed,但正则表达式替换了所有斜杠或仅替换最后一个斜杠:/

 find directory/ -name '*.xml' | xargs  -I 'file' echo "ln" file staging_ojs_pootle/file |sed -e '/^ln/s/(staging_ojs_pootle.*)[/](.*)/1.2/g'

问候

试试这个:

$ find directory/ -name '*.xml' |sed -r 'h;s|/|.|g;G;s|([^n]+)n(.+)|ln 2 staging_ojs_pootle/1|e'

例如:

$ mkdir -p /tmp/test
$ touch {1,2,3,4}.xml
# use /tmp/test as staging_ojs_pootle
$ find /tmp/test -name '*.xml' |sed -r 'h;s|/|.|g;G;s|([^n]+)n(.+)|ln 2 /tmp/test/1|e'
$ ls -al /tmp/test
total 8
drwxr-xr-x. 2 root root 4096 Jun 15 13:09 .
drwxrwxrwt. 9 root root 4096 Jun 15 11:45 ..
-rw-r--r--. 2 root root    0 Jun 15 11:45 1.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 2.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 3.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 4.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 .tmp.test.1.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 .tmp.test.2.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 .tmp.test.3.xml
-rw-r--r--. 2 root root    0 Jun 15 11:45 .tmp.test.4.xml
# if don NOT use the e modifier of s command, we can get the final command
$ find /tmp/test -name '*.xml' |sed -r 'h;s|/|.|g;G;s|([^n]+)n(.+)|ln 2 /tmp/test/1|' 
ln /tmp/test/1.xml /tmp/test/.tmp.test.1.xml
ln /tmp/test/2.xml /tmp/test/.tmp.test.2.xml
ln /tmp/test/3.xml /tmp/test/.tmp.test.3.xml
ln /tmp/test/4.xml /tmp/test/.tmp.test.4.xml

解释:

  1. 对于每个 XML 文件,请使用 h 将源文件名保留在 hold space 中。
  2. 使用 s|/|.|g 替换 XML 文件名的所有/ .
  3. 使用 Ghold space附加到 pattern space ,则pattern space CHANGED_FILENAMEnORIGIN_FILENAME
  4. 使用
  5. s|([^n]+)n(.+)|ln 2 staging_ojs_pootle/1|e' 将命令与 CHANGED_FILENAMEORIGIN_FILENAME 合并,然后使用 e 命令的修饰符执行上面组装的命令,这将完成实际工作。

希望这有帮助!

如果可以确定 XML 文件的名称不包含任何分词字符,则可以使用如下名称:

find directory -name "*.xml" | sed 'p;s///./' | xargs -n2 echo ln

最新更新