首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换xargs变量返回空字符串

替换xargs变量返回空字符串
EN

Stack Overflow用户
提问于 2017-06-15 07:31:35
回答 2查看 304关注 0票数 0

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

bash命令不起作用,我被替换部分卡住了。xargs中名为‘(${file/\//.})’的变量在替换代码文件中似乎是不可访问的

代码语言:javascript
复制
find directory/ -name '*.xml' | xargs  -I 'file' echo "ln" file staging_ojs_pootle/${file/\//.}

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

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

代码语言:javascript
复制
 find directory/ -name '*.xml' | xargs  -I 'file' echo "ln" file staging_ojs_pootle/file |sed -e '/^ln/s/\(staging_ojs_pootle.*\)[\/]\(.*\)/\1.\2/g'

问候

EN

回答 2

Stack Overflow用户

发布于 2017-06-15 13:25:19

试试这个:

代码语言:javascript
复制
$ find directory/ -name '*.xml' |sed -r 'h;s|/|.|g;G;s|([^\n]+)\n(.+)|ln \2 staging_ojs_pootle/\1|e'

例如:

代码语言:javascript
复制
$ 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

解释:

对于每个xml文件,在hold space.

  • the中使用

  • 保留原始文件名使用h将所有/替换为. Ghold space附加到pattern space,然后pattern spaces|([^\n]+)\n(.+)|ln \2 staging_ojs_pootle/\1|e'将命令与CHANGED_FILENAMEORIGIN_FILENAME合并,然后使用s命令的e修饰符执行上面组装的命令,这将进行实际工作。

希望这能有所帮助!

票数 0
EN

Stack Overflow用户

发布于 2017-06-15 16:37:05

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

代码语言:javascript
复制
find directory -name "*.xml" | sed 'p;s/\//./' | xargs -n2 echo ln
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44556247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档