JB.*_*JB. 1032
如果x是常量,则以下参数扩展执行子字符串提取:
b=${a:12:5}
Run Code Online (Sandbox Code Playgroud)
其中12是偏移量(从零开始),5是长度
如果数字周围的下划线是输入中的唯一下划线,则可以分两步删除前缀和后缀(分别):
tmp=${a#*_} # remove prefix ending in "_"
b=${tmp%_*} # remove suffix starting with "_"
Run Code Online (Sandbox Code Playgroud)
如果有其他下划线,无论如何它可能是可行的,尽管更棘手.如果有人知道如何在单个表达式中执行两个扩展,我也想知道.
所提出的两种解决方案都是纯粹的bash,没有涉及过程产生,因此非常快.
Fer*_*anB 651
使用剪切:
echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2
Run Code Online (Sandbox Code Playgroud)
更通用的:
INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING
Run Code Online (Sandbox Code Playgroud)
Joh*_*itb 91
通用解决方案,其中数字可以是文件名中的任何位置,使用第一个这样的序列:
number=$(echo $filename | egrep -o '[[:digit:]]{5}' | head -n1)
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是精确提取变量的一部分:
number=${filename:offset:length}
Run Code Online (Sandbox Code Playgroud)
如果您的文件名始终具有stuff_digits_...
您可以使用awk 的格式:
number=$(echo $filename | awk -F _ '{ print $2 }')
Run Code Online (Sandbox Code Playgroud)
除了数字之外,还有另一种解决方案,使用
number=$(echo $filename | tr -cd '[[:digit:]]')
Run Code Online (Sandbox Code Playgroud)
bro*_*179 86
只是尝试使用 cut -c startIndx-stopIndx
jpe*_*lli 33
如果有人想要更严格的信息,你也可以像这样在man bash中搜索它
$ man bash [press return key]
/substring [press return key]
[press "n" key]
[press "n" key]
[press "n" key]
[press "n" key]
Run Code Online (Sandbox Code Playgroud)
结果:
${parameter:offset} ${parameter:offset:length} Substring Expansion. Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter start? ing at the character specified by offset. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below). If offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter. Arithmetic expressions starting with a - must be separated by whitespace from the preceding : to be distinguished from the Use Default Values expansion. If length evaluates to a number less than zero, and parameter is not @ and not an indexed or associative array, it is interpreted as an offset from the end of the value of parameter rather than a number of characters, and the expan? sion is the characters between the two offsets. If parameter is @, the result is length positional parameters beginning at off? set. If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. Sub? string expansion applied to an associative array produces unde? fined results. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 is prefixed to the list.
PEZ*_*PEZ 20
基于jor的答案(这对我不起作用):
substring=$(expr "$filename" : '.*_\([^_]*\)_.*')
Run Code Online (Sandbox Code Playgroud)
use*_*062 19
我很惊讶这个纯粹的bash解决方案没有出现:
a="someletters_12345_moreleters.ext"
IFS="_"
set $a
echo $2
# prints 12345
Run Code Online (Sandbox Code Playgroud)
您可能希望将IFS重置为之前或unset IFS
之后的值!
nic*_*bot 15
这是我怎么做的:
FN=someletters_12345_moreleters.ext
[[ ${FN} =~ _([[:digit:]]{5})_ ]] && NUM=${BASH_REMATCH[1]}
Run Code Online (Sandbox Code Playgroud)
注意:以上是正则表达式,仅限于由下划线包围的五位数的特定场景.如果需要不同的匹配,请更改正则表达式.
fed*_*qui 12
遵循要求
我有一个带有x个字符的文件名,然后是一个五位数序列,两边都是一个下划线,然后是另一组x个字符.我想取5位数字并将其放入变量中.
我发现了一些grep
可能有用的方法:
$ echo "someletters_12345_moreleters.ext" | grep -Eo "[[:digit:]]+"
12345
Run Code Online (Sandbox Code Playgroud)
或更好
$ echo "someletters_12345_moreleters.ext" | grep -Eo "[[:digit:]]{5}"
12345
Run Code Online (Sandbox Code Playgroud)
然后用-Po
语法:
$ echo "someletters_12345_moreleters.ext" | grep -Po '(?<=_)\d+'
12345
Run Code Online (Sandbox Code Playgroud)
或者如果你想让它恰好适合5个字符:
$ echo "someletters_12345_moreleters.ext" | grep -Po '(?<=_)\d{5}'
12345
Run Code Online (Sandbox Code Playgroud)
最后,为了使它存储在变量中,只需要使用var=$(command)
语法.
Dar*_*ron 10
没有任何子流程,您可以:
shopt -s extglob
front=${input%%_+([a-zA-Z]).*}
digits=${front##+([a-zA-Z])_}
Run Code Online (Sandbox Code Playgroud)
一个非常小的变体也适用于ksh93.
小智 10
如果我们专注于以下概念:
"一个(一个或几个)数字的运行"
我们可以使用几个外部工具来提取数字.
我们可以很容易地删除所有其他字符,sed或tr:
name='someletters_12345_moreleters.ext'
echo $name | sed 's/[^0-9]*//g' # 12345
echo $name | tr -c -d 0-9 # 12345
Run Code Online (Sandbox Code Playgroud)
但如果$ name包含多个数字,则上述操作将失败:
如果"name = someletters_12345_moreleters_323_end.ext",则:
echo $name | sed 's/[^0-9]*//g' # 12345323
echo $name | tr -c -d 0-9 # 12345323
Run Code Online (Sandbox Code Playgroud)
我们需要使用常规表达式(正则表达式).
要在sed和perl中仅选择第一次运行(12345而不是323):
echo $name | sed 's/[^0-9]*\([0-9]\{1,\}\).*$/\1/'
perl -e 'my $name='$name';my ($num)=$name=~/(\d+)/;print "$num\n";'
Run Code Online (Sandbox Code Playgroud)
但我们也可以直接在bash (1)中做到:
regex=[^0-9]*([0-9]{1,}).*$; \
[[ $name =~ $regex ]] && echo ${BASH_REMATCH[1]}
Run Code Online (Sandbox Code Playgroud)
这允许我们提取
由任何其他文本/字符包围的任何长度的第一轮数字.
注意:regex=[^0-9]*([0-9]{5,5}).*$;
仅匹配5位数运行.:-)
(1):比为每个短文本调用外部工具更快.对于在大型文件中执行sed或awk内的所有处理并不快.
小智 9
这是一个前缀后缀解决方案(类似于JB和Darron给出的解决方案),它匹配第一个数字块,不依赖于周围的下划线:
str='someletters_12345_morele34ters.ext'
s1="${str#"${str%%[[:digit:]]*}"}" # strip off non-digit prefix from str
s2="${s1%%[^[:digit:]]*}" # strip off non-digit suffix from s1
echo "$s2" # 12345
Run Code Online (Sandbox Code Playgroud)
小智 9
shell cut - 打印字符串中特定范围的字符或给定部分
#方法1) 使用bash
str=2020-08-08T07:40:00.000Z
echo ${str:11:8}
Run Code Online (Sandbox Code Playgroud)
#方法2)使用剪切
str=2020-08-08T07:40:00.000Z
cut -c12-19 <<< $str
Run Code Online (Sandbox Code Playgroud)
#method3) 使用 awk 时
str=2020-08-08T07:40:00.000Z
awk '{time=gensub(/.{11}(.{8}).*/,"\\1","g",$1); print time}' <<< $str
Run Code Online (Sandbox Code Playgroud)
我的答案将更好地控制您想要从字符串中获得的内容。这是有关如何12345
从字符串中提取的代码
str="someletters_12345_moreleters.ext"
str=${str#*_}
str=${str%_more*}
echo $str
Run Code Online (Sandbox Code Playgroud)
如果您想提取具有任何字符abc
或任何特殊字符(如_
或 )的内容,这将更有效-
。例如:如果您的字符串是这样的,并且您想要之后someletters_
和之前的所有内容_moreleters.ext
:
str="someletters_123-45-24a&13b-1_moreleters.ext"
Run Code Online (Sandbox Code Playgroud)
使用我的代码,您可以准确地提及您想要的内容。解释:
#*
它将删除前面的字符串,包括匹配的键。这里我们提到的键是_
%
它将删除包括匹配键在内的以下字符串。这里我们提到的关键是'_more*'
自己做一些实验,你会发现这很有趣。
我喜欢sed
处理正则表达式群体的能力:
> var="someletters_12345_moreletters.ext"
> digits=$( echo $var | sed "s/.*_\([0-9]\+\).*/\1/p" -n )
> echo $digits
12345
Run Code Online (Sandbox Code Playgroud)
稍微更通用的选择是不要假设你有一个下划线_
标记数字序列的开头,因此例如剥离你在序列之前得到的所有非数字:s/[^0-9]\+\([0-9]\+\).*/\1/p
.
> man sed | grep s/regexp/replacement -A 2
s/regexp/replacement/
Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to
refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.
Run Code Online (Sandbox Code Playgroud)
更多相关信息,如果你对regexp不太自信:
s
适用于_s_ubstitute[0-9]+
匹配1+位数\1
链接到正则表达式输出的组n.1(组0是整个匹配,组1是在这种情况下括号内的匹配)p
flag是_p_rinting所有逃脱\
都是为了进行正则sed
表达式处理工作.
小智 6
鉴于test.txt是一个包含"ABCDEFGHIJKLMNOPQRSTUVWXYZ"的文件
cut -b19-20 test.txt > test1.txt # This will extract chars 19 & 20 "ST"
while read -r; do;
> x=$REPLY
> done < test1.txt
echo $x
ST
Run Code Online (Sandbox Code Playgroud)
许多过时的解决方案都需要管道和子壳来解决这个问题。从bash版本3(2004年发布)开始,它有一个内置的正则表达式比较运算符=~
。
input="someletters_12345_moreleters.ext"
# match: underscore followed by 1 or more digits followed by underscore
[[ $input =~ _([0-9]+)_ ]]
echo ${BASH_REMATCH[1]}
Run Code Online (Sandbox Code Playgroud)
输出:
12345
Run Code Online (Sandbox Code Playgroud)
请注意,如果您不太精通编写正则表达式,我建议您阅读掌握正则表达式。
如果您只需要弄清楚如何让 RegExp 工作,并且它与您的想法不符,请尝试 RegEx101.com 上的在线 GUI 并将“Flavor”设置为“PCRE”,以便获得 POSIX 风格的字符类就像[[:digit:]]
那样bash
使用。
归档时间: |
|
查看次数: |
1142601 次 |
最近记录: |