Bash

在 bash 腳本中拆分字元串

  • November 25, 2018

我正在從使用者那裡獲取一些輸入並檢查有關它的詳細資訊。

例子:

$HOME/Documents/test/one.txt

我把上面的字元串作為輸入,想找回來one.txt,還需要繼續one.txt

@Jordanm 已經為您提供了適用於任何字元串的規範答案。如果您正在專門處理路徑,您還可以使用程序basenamedirname

  basename - strip directory and suffix from filenames
  dirname - strip last component from file name

例如:

$ file="$HOME/Documents/test/one.txt"
$ dir=$(dirname "$file");
$ name=$(basename "$file");
$ echo "The file called $name is in the directory $dir"
The file called one.txt is in the directory /home/terdon/Documents/test

引用自:https://unix.stackexchange.com/questions/94213