Filenames

在中間列印部分文件名

  • March 7, 2022

我有幾個文件的名稱為:

ID_Italy.txt
ID2_USA.txt
ID3_Germany.txt
.....

如果我想在 _ 之前列印,我可以:

for file in *.txt; do print "${file%_*}";done

輸出:

ID
ID2
ID3

如果我想列印並刪除副檔名:

for file in *.txt; do print "${file%.*}";done

輸出:

ID_Italy
ID2_USA
ID3_Germany

但是,我只想取介於 _ 和 . 並具有以下輸出:

Italy
USA
Germany

那怎麼列印?

已編輯,沒有 tempvar:

$ for file in *.txt; do echo "${file//?(.*|*_)/}";done
USA
Germany
Italy
#!/bin/bash
 for f in *.txt ; do
 f="${f%.*}"
 echo ${f##*_}
done

我使用命令創建了文件,touch然後執行了fx腳本:

$ touch ID_Italy.txt
$ touch ID2_USA.txt
$ touch ID3_Germany.txt
$./fx
USA
Germany
Italy

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