获取点分隔字符串的第一个值(Bash)

huangapple go评论48阅读模式
英文:

get first value of a dot separated string (Bash)

问题

chicken.fasta.count.sorted.topthree.txt这是一个在bash中的字符串,由点号分隔,并且你想要获取第一个点号之前的部分。你只需获取子字符串 'chicken' 并将它存储在一个变量中。

可以使用以下方式来实现:

s="chicken.fasta.count.sorted.topthree.txt"
animal_name="${s%%.*}"

这将把 'chicken' 存储在变量 animal_name 中。

英文:

Hey so I have a string in bash named

chicken.fasta.count.sorted.topthree.txt It's a string delimited by dots and I want the value before the first dot.

I just want the substring 'chicken' and I want to store it in a variable.

Can someone show me the way?

s="$chicken.fasta.count.sorted.topthree.txt"
animal_name="${s%.*}

答案1

得分: 1

使用cut命令可能如下:

echo "chicken.fasta.count.sorted.topthree.txt" | cut -d '.' -f 1
英文:

Maybe using cut command:

echo "chicken.fasta.count.sorted.topthree.txt | cut -d '.' -f 1

答案2

得分: 0

使用以下任一Perl一行命令:

echo 'chicken.fasta.count.sorted.topthree.txt' | perl -lne 'print /([^.]*)/'

echo 'chicken.fasta.count.sorted.topthree.txt' | perl -F'[.]' -lane 'print $F[0]'

/([^.]*)/:匹配具有任何非句点字符([^.])重复0次或更多次(*)的模式。模式使用括号捕获,然后传递给print,将其打印出来。

Perl一行命令使用以下命令行标志:

  • -e:告诉Perl在行内查找代码,而不是在文件中查找。
  • -n:逐行循环处理输入,默认将其分配给$_
  • -l:在执行行内代码之前删除输入行分隔符(在*NIX上默认为\n),并在打印时附加它。
  • -a:将$_分割为数组@F,可以使用空格或在-F选项中指定的正则表达式进行分割。
  • -F'[.]':在句点(.)上进行分割,而不是在空格上进行分割。

另请参阅:

英文:

Use either of these Perl one-liners:

echo 'chicken.fasta.count.sorted.topthree.txt' | perl -lne 'print /([^.]*)/'

or

echo 'chicken.fasta.count.sorted.topthree.txt' | perl -F'[.]' -lane 'print $F[0]'

/([^.]*)/ : match the pattern that has any non-dot character ([^.]) repeated 0 or more times (*). The pattern is captured with parentheses and pass to print, which prints it.

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.
-F'[.]' : Split into @F on a literal dot (.), rather than on whitespace.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start

huangapple
  • 本文由 发表于 2023年2月10日 04:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定