BASH: How to extract substring that is surrounded by specific text

前端 未结 3 1434
囚心锁ツ
囚心锁ツ 2021-01-28 22:42

I am trying to extract numbers from file names that follow a specific pattern:

file-8923489_something.txt
another_file-8923489_something.txt
some-other_file-8923         


        
3条回答
  •  误落风尘
    2021-01-28 23:35

    With grep:

    $ echo "file-8923489_something.txt
    another_file-8923489_something.txt
    some-other_file-8923489_something.txt" | grep -Po '(?<=file-)\d+'
    8923489
    8923489
    8923489
    

    Or with pure bash:

    d="your_string"
    d1=${d%_*}
    your_final_string=${d1##*-}
    

    Test

    $ d="file-8923489_something.txt"
    $ d1=${d%_*}
    $ echo $d1
    file-8923489
    $ echo ${d1##*-}
    8923489
    
    $ d="some-other_file-8923489_something.txt"
    $ d1=${d%_*}
    $ echo $d1
    some-other_file-8923489
    $ echo ${d1##*-}
    8923489
    
    $ d="another_file-8923489_something.txt"
    $ d1=${d%_*}
    $ echo $d1
    another_file-8923489
    $ echo ${d1##*-}
    8923489
    

提交回复
热议问题