有没有一种方法可以告诉sed忽略符号链接?

6

我有一个目录A,里面有许多扩展名为.xml的文件,我需要进行搜索和替换。在A中有几个符号链接(也带有.xml扩展名),它们链接到A中的某些文件。我尝试运行sed -i 's/search_regexp/replacement_string/' *.xml,但当它遇到符号链接时会失败并显示如下错误:

 sed: ck_follow_symlink: couldn't lstat file.xml: No such file or directory

一种解决方案是循环遍历我实际想要修改的文件,并在每个文件上调用sed,但有没有办法告诉sed忽略符号链接?还是只跟随它们并修改链接的文件?
2个回答

5

@piokuc已经提到了跟随符号链接的选项,下面是如何使用find忽略它们:

find /path/to/dir/ -type f -name "*.xml" ! -type l -exec sed -i 's/search_regexp/replacement_string/' {} \;

或者,稍微更有效:

find /path/to/dir/ -type f -name "*.xml" ! -type l | xargs sed -i 's/search_regexp/replacement_string/'
< p > ! -type l 部分表示“不是符号链接”


符号链接是否被视为“常规文件”(属于-type f)?我使用了不带! -type l-type f选项运行了find命令,并过滤掉了符号链接。我想知道是否实际上需要使用! -type l - fo_x86
@fo_x86,这也是我的猜测(你只需要-type f),但我认为最好还是保险起见。 - sampson-chen

2

有一个选项可以实现这个功能(man sed):

       --follow-symlinks

          follow symlinks when processing in place

我使用的sed版本是4.1.5:

ariadne{/tmp}:310 --> sed --help | grep follow
  --follow-symlinks
                 follow symlinks when processing in place
ariadne{/tmp}:311 --> sed --version           
GNU sed version 4.1.5
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.
ariadne{/tmp}:312 --> uname -a
Linux ariadne 2.6.34.10-0.6-desktop #1 SMP PREEMPT 2011-12-13 18:27:38 +0100 x86_64 x86_64 x86_64 GNU/Linux
ariadne{/tmp}:313 --> 

这个选项在 sed 4.2 中是新的吗?我正在使用 4.1.5 (我很想升级,但是我的公司系统管理员拒绝了)。我在其他地方读到了这个选项,但在 man 手册中没有找到它。 - fo_x86
我已经有了4.1.5版本,选项在那里。 - piokuc
@fo_x86 不知道,也许是构建时没有配置该选项?我在我的答案中添加了有关我的 sed 版本的信息。 - piokuc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接