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

前端 未结 3 1433
囚心锁ツ
囚心锁ツ 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:26

    Using pre BASH regex:

    x="some-other_file-8923489_something.txt"
    [[ "$x" =~ file-([0-9]*)_something ]] && echo ${BASH_REMATCH[1]}
    8923489
    

    OR this grep -P will also work:

    grep -oP "file-\K\d+(?=_something)" file
    8923489
    8923489
    8923489
    

    OR using awk:

    awk -F 'file-|_something' '{print $2}' file
    8923489
    8923489
    8923489
    

提交回复
热议问题