0

我对 bash 脚本很陌生,所以这可能是个很愚蠢的问题,但它就在这里。想法如下:将文件的基本名称保存日志中->移动文件->使用日志移回原始位置。

basename $filename >> /directory/log
mv $filename /directory

到目前为止一切顺利,但我对如何使用该日志文件取回文件感到很困惑。basename甚至是正确的使用方法吗?我的想法是使用grep在日志中查找文件名,但是如何在mv末尾获取该输出?

mv $filename ???

我在正确的轨道上吗?搞砸了一些非常基本的东西?

4

3 回答 3

0

如果您需要从文件中获取字符串并在某些命令中使用它,那么grep就可以了

mv $filename `grep <your-grep-pattern> <you-logfile>`

如果日志文件包含匹配的正确数据,这将执行适当的操作。

于 2012-11-26T15:23:16.323 回答
0

像这样的东西?

#set a variable saving the filename but not path of a file. 
MY_FILENAME=$(basename $filename)
echo $MY_FILENAME >> /directory/log
mv $MY_FILENAME /diectroy/.

# DO STUFF HERE
# to your file here 

#Move the file to the PWD. 
mv /directory/${MY_FILENAME} .
unset $MY_FILENAME 
      #unseting variable when you are done with them, while not always 
      #not always necessary, i think is a good practice. 

相反,如果要将文件移回 orgianl 位置而不是 PWD,则第二个 mv 语句将如下所示。

mv /directory/${MY_FILENAME} $filename

此外,如果由于某些范围问题,当您向后移动时您没有可用的本地 var,并且确实需要从文件中读取它,您应该这样做:

 #set a variable saving the filename but not path of a file. 
MY_FILENAME=$(basename $filename)
echo "MY_FILENAME = " $MY_FILENAME >> /directory/log
# I'm tagging my var with some useful title so it is easier to grep for it later
mv $MY_FILENAME /diectroy/.

# DO STUFF HERE
# to your file here 

#Ive somehow forgotten my local var and need to get it back.
MY_FILENAME=$(cat /directory/log | grep "^MY_FILENAME = .*" | awk '{print $3}');
#inside the $() a cat the file to read it
# grep on "^MY_FILENAME = .*" to get the line that starts with the header i gave my filename
# and awk to give me the third token ( I always use awk over cut out of preference, cut would work also. 
# This assumes you only write ONE filename to the log, 
# writing more makes things more complicated

mv /directory/${MY_FILENAME} $filename
unset $MY_FILENAME 
于 2012-11-26T15:23:16.533 回答
0

让我们以文件httpd.conf为例,它的位置在目录中/etc/httpd/conf/

$ ls /etc/httpd/conf/httpd.conf
/etc/httpd/conf/httpd.conf

该命令basename去除文件的路径,只返回文件名(和扩展名)

$ basename /etc/httpd/conf/httpd.conf
httpd.conf

所以当你这样做时:

basename $filename >> /directory/log

您正在创建一个仅包含文件名的日志文件,您将无法使用/directory/log该文件将文件移回其原始位置,因为您使用该basename命令剥离了该信息。

你会想做这样的事情:

echo $filename >> /directory/log
mv $filename /directory

所以现在/directory是文件的新位置并/directory/log包含文件的原始位置。

于 2012-11-26T15:23:51.160 回答