You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ksh脚本仅复制指定目录下的*.log文件并保留结构与时间戳

修改KSH脚本以仅复制指定日志文件并保留目录结构和时间戳

以下是修正后的脚本,实现仅复制$PARENT_DIR下所有.log文件到$TARGET_DIR,同时保留原有的目录结构和文件时间戳:

#!/bin/ksh
# Input arguments
PARENT_DIR=$1
TARGET_DIR="/output/ndc_grid/target/folder/log_dump"

# Check if parent directory exists
if [ ! -d "$PARENT_DIR" ]; then
  echo "Parent directory $PARENT_DIR does not exist."
  exit 1
fi

# Check if target directory exists, if not create it
if [ ! -d "$TARGET_DIR" ]; then
  echo "Target directory $TARGET_DIR does not exist. Creating it..."
  mkdir -p "$TARGET_DIR"
fi

# Copy only *.log files while preserving directory structure and timestamps
echo "Copying *.log files with directory structure..."
find "$PARENT_DIR" -type f -name "*.log" -exec sh -c '
  for file do
    # Extract path relative to PARENT_DIR
    rel_path="${file#$PARENT_DIR/}"
    target_file="$TARGET_DIR/$rel_path"
    # Create target directory if it doesn'\''t exist
    mkdir -p "$(dirname "$target_file")"
    # Copy file with preserving timestamps and permissions
    cp -p "$file" "$target_file"
  done
' sh {} +

echo "All *.log files have been copied to $TARGET_DIR with original directory structure"

关键修改说明

  • 精准匹配日志文件:给*.log添加双引号,避免shell提前解析通配符,确保只筛选文件名以.log结尾的文件
  • 提升处理效率:使用-exec sh -c '...' sh {} +批量处理找到的文件,减少重复启动进程的开销
  • 保留目录结构:通过${file#$PARENT_DIR/}提取文件相对于源目录的路径,保证目标目录下的层级和源目录完全一致
  • 自动创建目标目录:用mkdir -p "$(dirname "$target_file")"自动生成文件所需的上级目录,避免复制失败
  • 保留文件属性:用cp -p替代冗余的cp -pr(单个文件无需递归参数r),完整保留文件的时间戳、权限和所有者信息

内容的提问来源于stack exchange,提问作者Arpit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:35:02