0

我正在使用 bash 遍历文件文件夹,但我需要剪切前面的路径。例如,如果我有这个'/temp/test/filename',我想切断'/temp/test/'并将文件名存储到一个变量中,这样我就可以在其中写入一个带有文件名的日志。

谁能帮我吗?问题是变量 temp 始终为空。

这是我的 bash 代码:

#!/bin/bash

for file in /temp/test/*
do
    if [[ ! -f "$file" ]]
    then
        continue
    fi

    temp="$file"|cut -d'/' -f3

    $file > /var/log/$temp$(date +%Y%m%d%H%M%S).log
done

exit
4

1 回答 1

1

试试看:

$ x=/temp/test/filename
$ echo ${x##*/}
filename

另一种解决方案是使用basename

$ basename /temp/test/filename
filename

第一个解决方案是参数扩展,它是bash内置的,所以我们提高了性能。

你的线temp="$file"|cut -d'/' -f3坏了。

  • 当您想将命令的输出存储在变量中时,您应该这样做var=$(command)
  • 您需要使用( ) 或使用将值传递给STDIN命令的here-string<<<echo value | command

最后,如果你想使用cut

$ temp=$(cut -d/ -f4 <<< /temp/test/filename)
$ echo $temp
filename
于 2012-10-17T22:36:08.227 回答