shell 用文件递归接触文件

zlwx9yxi  于 12个月前  发布在  Shell
关注(0)|答案(3)|浏览(130)

我有一个目录,其中包含子目录和其他文件,并希望更新日期/时间戳递归与日期/时间戳的另一个文件/目录。
我知道:

touch -r file directory

更改文件或目录的日期/时间戳,但不更改其中的任何内容。还有一个find版本,它是:

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

如果我能指定实际的文件/目录并使用另一个日期/时间戳,这将很好地工作。有没有一个简单的方法来做到这一点?更好的是,有没有一种方法可以避免在进行“CP”时更改/更新时间戳?

jvidinwx

jvidinwx1#

更好的是,有没有一种方法可以避免在进行“CP”时更改/更新时间戳?
是,使用cp-p选项:

  • 我靠
    同--preserve=mode,ownership,timestamps

--保存

保留指定的属性(默认值:模式、所有权、时间戳),如果可能的话,附加属性:context,links,xattr,all

示例

$ 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") {} \;

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

ldioqlga

ldioqlga2#

正如fedorqui所说,cp -p是首选,但也许你忘记了-p,需要递归地将时间戳替换为原始时间戳,而无需重新复制所有文件。我尝试使用$()嵌套shell命令,但sed没有正确返回修改后的字符串。下面是一个有效的修改:

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

这假定源的重复文件/文件夹树:/Source和目的地:/Destination

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

ui7jx7zq3#

除了'cp -p'之外,您还可以使用'touch -t'(重新)创建旧的时间戳。有关详细信息,请参阅“touch”的手册页。

touch -t 200510071138 old_file.dat

相关问题