Extract substring in Bash

前端 未结 22 1894
别那么骄傲
别那么骄傲 2020-11-22 11:02

Given a filename in the form someletters_12345_moreleters.ext, I want to extract the 5 digits and put them into a variable.

So to emphasize the point, I

相关标签:
22条回答
  • 2020-11-22 11:39

    similar to substr('abcdefg', 2-1, 3) in php:

    echo 'abcdefg'|tail -c +2|head -c 3
    
    0 讨论(0)
  • 2020-11-22 11:39

    shell cut - print specific range of characters or given part from a string

    #method1) using bash

     str=2020-08-08T07:40:00.000Z
     echo ${str:11:8}
    

    #method2) using cut

     str=2020-08-08T07:40:00.000Z
     cut -c12-19 <<< $str
    

    #method3) when working with awk

     str=2020-08-08T07:40:00.000Z
     awk '{time=gensub(/.{11}(.{8}).*/,"\\1","g",$1); print time}' <<< $str
    
    0 讨论(0)
  • 2020-11-22 11:40

    Given test.txt is a file containing "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
    
    0 讨论(0)
  • 2020-11-22 11:42

    Generic solution where the number can be anywhere in the filename, using the first of such sequences:

    number=$(echo $filename | egrep -o '[[:digit:]]{5}' | head -n1)
    

    Another solution to extract exactly a part of a variable:

    number=${filename:offset:length}
    

    If your filename always have the format stuff_digits_... you can use awk:

    number=$(echo $filename | awk -F _ '{ print $2 }')
    

    Yet another solution to remove everything except digits, use

    number=$(echo $filename | tr -cd '[[:digit:]]')
    
    0 讨论(0)
提交回复
热议问题