2013-11-22 187 views
1

以下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 

可有人建议如何访问目录路径作为命令行参数?

+1

'./test.sh * .txt'将在test.sh被调用之前使外壳扩展通配符,因此它在功能上等同于'./test.sh file1.txt file2.txt file3.txt etc ..' –

回答

2

你的第一行应该是:

FILE=`find "[email protected]" -type f -name "abc.txt"` 

通配符将调用脚本之前进行扩展,所以你需要使用"[email protected]"让所有它扩展到目录,并通过这些作为参数find

0

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

有你这样的脚本:

#!/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:了解如何SED可以直接使用-exec选项发现自己被调用。

+0

该目录的名称不是“2011.11”,而是“2011.11.10”。他需要通配符才能找到带有任何后缀的目录。 – Barmar

+0

@Barmar:啊谢谢,我错过了这一点。现在编辑。 – anubhava