sed 选项在查找/替换期间保留文件时间?

sed 选项在查找/替换期间保留文件时间?

我正在尝试修改一些 Autotool 文件,因为一个项目不遵守我的CFLAGSCXXFLAGSLDFLAGS。我找到了一些可能使用 进行更改的区域greplibtool: link当我调整 Autotool 文件时:

$ sed -i "" 's|$CC -dynamiclib|$CC -dynamiclib -force_cpusubtype_ALL|g' configure configure.ac

其结果是:

WARNING: 'aclocal-1.14' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127

touch -t 19700101 configure.ac没有解决问题。

我使用的是旧版 OS X 系统,它没有工具所需的工具。我 grepedsed(1)手册页,但我没有看到保留文件时间的选项。

我如何指示sed保存文件时间?

答案1

sed在任何实现中都不太可能做到这一点。命令

touch -t 19700101 configure.ac

告诉touch使用以下命令将时间戳设置为虚假日期(因为仅给出了 8 位数字)

  • 毫米= 19
  • 直接差分= 70
  • = 01
  • 毫米= 01

你可能打算

touch -t 197001010000 configure.ac

(19700101 为 8 位数字,0000 为 4 位数字),尽管这样可能会遇到时区问题。无论如何,不​​太可能需要将文件的时间戳重置得这么早。我只需将其重置为原始值即可。

例如(我通常这样做持续专业发展),可以编写一个脚本将时间戳从原始文件复制到编辑的文件中。以下是适用于 OSX 的示例脚本:

#!/bin/sh
usage() {
    echo "usage: $0 source target" >&2
    exit 1
}

[ $# = 2 ] || usage

[ -L "$1" ] && usage
[ -L "$2" ] && usage

[ -f "$1" ] || usage
[ -f "$2" ] || usage

SOURCE=$(stat -t "%Y%m%d%H%M.%S" -f "%Sm" "$1")
ls -l $2
touch -t "$SOURCE" "$2"
ls -l $2

有趣的是(命令行stat不是标准化),OSX 版本的stat比 Linux 更适合这个特定的应用程序stat对于 Linux,可以通过从列表中获取时间戳来执行类似操作ls -l,并使用非标准-d选项touch应用时间戳。

答案2

您可以混合使用sed -itouch来保留初始时间戳。例如:

file=file-to-edit

sed -i .bak 's|...' "$file"
touch -r "$file.bak" "$file"
# rm "$file.bak"

相关内容