以文件方式递归地触摸文件

问题描述 投票:0回答:3

我有一个包含子目录和其他文件的目录,并且想使用另一个文件/目录的日期/时间戳递归更新日期/时间戳。

我知道:

touch -r file directory

与其他文件或目录一起更改日期/时间戳,但其中不更改任何内容。还有查找版本:

find . -exec touch -mt 201309300223.25 {} +\;

如果我可以指定实际的文件/目录并使用另一个日期/时间戳,那么效果会很好。有没有一种简单的方法可以做到这一点?更好的是,有没有办法避免在执行“cp”时更改/更新时间戳?

bash shell file touch
3个回答
2
投票

更好的是,有没有办法避免在执行“cp”时更改/更新时间戳?

是的,将

cp
-p
选项一起使用:

-p

与--preserve=模式、所有权、时间戳相同

--保存

保留指定的属性(默认: 模式、所有权、时间戳),如果可能的话附加属性: 上下文、链接、xattr、所有

示例

$ ls -ltr
-rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
$ cp old_file not_maintains    <----- does not preserve time
$ cp -p old_file do_maintains  <----- does preserve time
$ ls -ltr
total 28
-rwxrwxr-x 1 me me  368 Apr 24 10:50 old_file
-rwxrwxr-x 1 me me  368 Apr 24 10:50 do_maintains   <----- does preserve time
-rwxrwxr-x 1 me me  368 Sep 30 11:33 not_maintains  <----- does not preserve time

要基于另一个路径上的对称文件递归地

touch
目录上的文件,您可以尝试如下操作:

find /your/path/ -exec touch -r $(echo {} | sed "s#/your/path#/your/original/path#g") {} \;

它对我不起作用,但我想这是一个多尝试/测试的问题。


0
投票

正如 fedorqui 所说,

cp -p
是首选,但也许你忘记了 -p 并且需要递归地替换时间戳而不重新复制所有文件。我尝试使用 $() 嵌套 shell 命令,但 sed 未正确返回修改后的字符串。这是一个有效的修改:

find /Destination -exec bash -c 'touch -r "${0/Destination/Source}" "$0"' {} \;

这假设源:

/Source
和目标:
/Destination

的重复文件/文件夹树
  1. find
    在目标中搜索所有文件和目录(需要时间戳),并为每个结果运行一个命令。
  2. -exec ... {}
  3. 使用 bash 执行 shell 命令。
  4. bash -c ' ... '
  5. 保存查找结果。
  6. $0
  7. 使用 bash 替换命令
    touch -r {timestamped_file} {file_to_stamp}
    适当地设置时间戳源。
    引用源目录和目标目录来处理带空格的目录。

-1
投票

${string/search/replace}

© www.soinside.com 2019 - 2024. All rights reserved.