如何在 unix 上使用 shell 脚本替换 for...in 循环中的部分文件路径?

发布于 2024-11-19 01:34:20 字数 784 浏览 2 评论 0原文

需要很大的帮助。我完全被这个问题困住了。我正在循环(递归)目录中的所有文件并打印文件列表。比如:

# srcDir="input received from command line"
# tgtDir="input received from command line"

for listItem in `find ${srcDir}`
do
    if [[ -f ${listItem} ]]
    then
        echo ${listItem} # **** what to put here ****
    fi
done

打印列表时,我想将文件的路径从 srcDir 替换为 tgtDir。比如:

# let's assume that srcDir="/home/user"
# and tgtDir="/tmp/guest"
# srcDir has the following structure
file1.txt
dir1_1/file1a.txt
dir1_1/file1b.txt

# so the actual output of the script will be
/home/user/file1.txt
/home/user/dir1_1/file1a.txt
/home/user/dir1_1/file1b.txt

# but I want it to print as
/tmp/guest/file1.txt
/tmp/guest/dir1_1/file1a.txt
/tmp/guest/dir1_1/file1b.txt

我希望你明白了。请指教。

Need help big-time. I am totally stuck on this one. I am looping (recursively) through all the files in a directory and printing a list of files. Something like:

# srcDir="input received from command line"
# tgtDir="input received from command line"

for listItem in `find ${srcDir}`
do
    if [[ -f ${listItem} ]]
    then
        echo ${listItem} # **** what to put here ****
    fi
done

When printing the list, I want to replace the path of the file from the srcDir to tgtDir. Something like:

# let's assume that srcDir="/home/user"
# and tgtDir="/tmp/guest"
# srcDir has the following structure
file1.txt
dir1_1/file1a.txt
dir1_1/file1b.txt

# so the actual output of the script will be
/home/user/file1.txt
/home/user/dir1_1/file1a.txt
/home/user/dir1_1/file1b.txt

# but I want it to print as
/tmp/guest/file1.txt
/tmp/guest/dir1_1/file1a.txt
/tmp/guest/dir1_1/file1b.txt

I hope you got the idea. Please advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空 2024-11-26 01:34:20

看起来像是 bash 字符串操作 的工作:

srcDir="/home/user"
tgtDir="/tmp/guest"
listItem="/home/user/file1.txt"
echo ${listItem/$srcDir/$tgtDir}

Looks like a job for bash string operations:

srcDir="/home/user"
tgtDir="/tmp/guest"
listItem="/home/user/file1.txt"
echo ${listItem/$srcDir/$tgtDir}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文