我有一个文件名,格式如下:
system-source-yyyymmdd.dat
我想使用“ - ”作为分隔符来解析文件名的不同部分。
$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2
source
"-d"指定分隔符,"-f"指定您需要的字段号。
我认为一个漂亮而简洁的方法是只使用内置函数将其放入数组中。
var='system-source-yyyymmdd.dat'
parts=(${var//-/ })
然后,您可以在数组中找到那些部分...
echo ${parts[0]} ==> system
echo ${parts[1]} ==> source
echo ${parts[2]} ==> yyyymmdd.dat
注意:如果文件名包含空格、引号或者反引号等“奇怪”的字符,此方法将无法生效……
根据您的需求,awk比cut更加灵活。以下是一个简单的示例:
# echo "system-source-yyyymmdd.dat" \
|awk -F- '{printf "System: %s\nSource: %s\nYear: %s\nMonth: %s\nDay: %s\n",
$1,$2,substr($3,1,4),substr($3,5,2),substr($3,7,2)}'
System: system
Source: source
Year: yyyy
Month: mm
Day: dd
cut
命令。
例如:echo "system-source-yyyymmdd.dat" | cut -f1 -d'-'
将提取第一位。
更改-f
参数的值以获取适当的部分。
这里有一个关于Cut命令的指南。
oIFS=$IFS IFS=- file="system-source-yyyymmdd.dat" set $file IFS=$oIFS echo "Source is $2"
最简单(也是我认为最好的方法)就是直接使用read
:
$ IFS=-. read system source date ext << EOF
> foo-bar-yyyymmdd.dat
> EOF
$ echo $system
foo
$ echo $source $date $ext
bar yyyymmdd dat
这个主题有很多变化,其中许多是依赖于 shell 的:
bash$ IFS=-. read system source date ext <<< foo-bar-yyyymmdd.dat
echo "$name" | { IFS=-. read system source date ext
echo In all shells, the variables are set here...; }
echo but only in some shells do they retain their value here
var = "system-source-yyyymmdd.dat" | cut -d'-' -f2
是不起作用的。 - EsseTi