我可以在 shell 命令行中执行此操作。
filename="/home/vikrant_singh_rana/testing/110001_ABC Traffic_04May2020_header_only.csv"
output_filename=$(basename "$filename")
cat "/home/vikrant_singh_rana/testing/110001_ABC Traffic_04May2020_header_only.csv" > /home/vikrant_singh_rana/enrichment_files/"$output_filename"
它能够读取给定文件'/home/vikrant_singh_rana/testing'
并将同名文件写入其他目录'/home/vikrant_singh_rana/enrichment_files'
当我在 shell 脚本中做同样的事情时。它不工作
#!/bin/bash
# Go to where the files are located
filedir=/home/vikrant_singh_rana/testing/*
first='yes'
#reading file from directory
for filename in $filedir; do
#echo $filename
output_filename=$(basename "$filename")
#echo $output_filename
#done
done > /home/vikrant_singh_rana/enrichment_files/"$output_filename"
运行此程序时我收到此错误
/home/vikrant_singh_rana/enrichment_files/: Is a directory
答案1
您错误地使用了路径名扩展 ( *
)。正如 muru 的评论所述,您在循环内部和外部混合使用变量。
#! /bin/bash
source_dir_path='/home/vikrant_singh_rana/testing'
target_dir_path='/home/vikrant_singh_rana/enrichment_files'
cd "$source_dir_path" || exit 1
for filename in *; do
target_path="${target_dir_path}/${filename}"
test -f "$target_path" && { echo "File '${filename}' exists; skipping"; continue; }
cp -p "$filename" "$target_path"
done