2016-08-15 64 views
1

我想分割一个字符串使用IFS看在许多地方提供的例子。我想分裂之后阵列最后一个元素,我做以下实现的目标:坏的数组下标,而在分裂一个字符串

path_to_file="/home/user/path/to/fileName.txt"; 
    IFS='/' read -ra split_path <<< "$path_to_file"; 
    file_name="${split_path[-1]}"; 

它给出了空间,在数组中的单个元素分开整个字符串。当我运行最后一条命令时,出现错误消息“-bash:split_path:bad array subscript”。我在做什么错了,而不是给我在不同的索引数组中的分隔元素。

回答

4

bash 3.x不理解-1表示数组的最后一个元素。你想

echo "${split_path[${#split_path[@]}-1]}" 

通知还引用。

正如其他人所指出的那样,basename可能是你的钱更好的运行,或${path_to_file##*/}

+1

'$ {path_to_file ## * /}'。 '-1'应该可以在更新的bash版本中工作。 (它在4.3.11中适用于我) – PSkocik

+0

@PSkocik感谢您的更正。是的,这是Bash 3,我想这是OP正在努力的。 – tripleee

+0

虽然我的Bash版本是4.1.2。你的答案是我正在寻找的。 – Prometheus

1

with basename;

path_to_file="/home/user/path/to/fileName.txt"; 
file_name=$(basename "$path_to_file") 
echo $file_name 

with awk;

path_to_file="/home/user/path/to/fileName.txt"; 
file_name=$(echo $path_to_file | awk -F/'{print $NF}') 
echo $file_name 

或while循环;

path_to_file="/home/user/path/to/fileName.txt"; 
while IFS='/' read -ra split_path ; do 
file_name="${split_path[-1]}"; 
echo $file_name 
done <<<$path_to_file 
+0

包含文件名的变量应该总是用双引号。 – tripleee