我有几个文件的名称为:
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
如何打印它?
答案1
编辑后,没有临时变量:
$ for file in *.txt; do echo "${file//?(.*|*_)/}";done
USA
Germany
Italy
答案2
如果您使用与 Bash 不同的 zsh(支持嵌套参数替换),您可以执行以下操作:
for file in ./*.txt; do
print "${${file%.txt}#*_}"
done
或者在 Bash 中使用数组解决方案:
for file in ./*.txt; do
{ IFS='_.' arr=( $file ); printf "%s\n" "${arr[2]}"; }
done
答案3
#!/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
答案4
bash
:
for f in ID[0-9_]*[A-Za-z].txt
do
[[ "$f" =~ _([^.]+) ]] && printf "%s\n" "${BASH_REMATCH[1]}"
done
标准POSIX
sh
:
for f in ID[0-9_]*[A-Za-z].txt
do IFS='_'; set -- $f; printf "%s\n" "${2%.*}"
done