【问题标题】:directory path as command line argument in bash目录路径作为bash中的命令行参数
【发布时间】:2013-12-07 17:36:53
【问题描述】:

以下 bash 脚本从给定的目录路径中找到一个 .txt 文件,然后从 .txt 文件中更改一个单词(将山变为海)

#!/bin/bash
FILE=`find /home/abc/Documents/2011.11.* -type f -name "abc.txt"`
sed -e 's/mountain/sea/g' $FILE 

在这种情况下,我得到的输出是可以的。 我的问题是,如果我想将目录路径作为命令行参数,那么它就不起作用。假设,我将我的 bash 脚本修改为:

#!/bin/bash
FILE=`find $1 -type f -name "abc.txt"`
sed -e 's/mountain/sea/g' $FILE 

然后像这样调用它:

./test.sh /home/abc/Documents/2011.11.*

错误是:

./test.sh: line 2: /home/abc/Documents/2011.11.10/abc.txt: Permission denied

谁能建议如何将目录路径作为命令行参数访问?

【问题讨论】:

  • ./test.sh *.txt 将使 shell 在 test.sh 被调用之前扩展该通配符,因此它在功能上与 ./test.sh file1.txt file2.txt file3.txt etc...

标签: linux bash directory command-line-arguments


【解决方案1】:

您无需将.* 传递给您的脚本。

让你的脚本是这样的:

#!/bin/bash

# some sanity checks here
path="$1"

find "$path".* -type f -name "abc.txt" -exec sed -i.bak 's/mountain/sea/g' '{}' \;

然后像这样运行它:

./test.sh "/home/abc/Documents/2011.11"

PS:看看如何使用 -exec 选项直接从 find 本身调用 sed。

【讨论】:

  • 目录名不是2011.11,而是2011.11.10。他需要通配符才能找到任何后缀的目录。
【解决方案2】:

你的第一行应该是:

FILE=`find "$@" -type f -name "abc.txt"`

通配符会在调用脚本之前被展开,因此您需要使用"$@" 来获取它展开到的所有目录并将这些作为参数传递给find

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    相关资源
    最近更新 更多