Warm tip: This article is reproduced from serverfault.com, please click

bash-使用Shell脚本在字符串中查找文件扩展名

(bash - Finding a file extension in a string using shell script)

发布于 2020-11-29 09:55:26

我有一个长字符串,其中包含文件名。我只想返回文件名。

如何在Shell脚本中执行此操作,即使用sed,awk等?

以下内容在python中有效,但我需要它在shell脚本中有效。

import re

def find_filename(string, match):
    string_list = string.split()
    match_list = []
    for word in string_list:
        if match in word:
            match_list.append(word)
    #remove any characters after file extension
    fullfilename = match_list[0][:-1]
    #get just the filename without full directory
    justfilename = fullfilename.split("/")
    return justfilename[-1]


mystr = "the string contains a lot of irrelevant information and then a filename: /home/test/this_filename.txt: and then more irrelevant info"
file_ext = ".txt"

filename =  find_filename(mystr, file_ext)
print(filename)

this_filename.txt

编辑添加外壳脚本要求

我会这样称呼shell脚本:

./test.sh "the string contains a lot of irrelevant information and then a filename: /home/test/this_filename.txt: and then more irrelevant info" ".txt"

test.sh

#!/bin/bash

longstring=$1
fileext=$2
echo $longstring
echo $fileext
Questioner
colebod209
Viewed
22
Cyrus 2020-11-29 18:23:03

bash和正则表达式:

#!/bin/bash

longstring="$1"
fileext="$2"
regex="[^/]+\\$fileext"

[[ "$longstring" =~ $regex ]] && echo "${BASH_REMATCH[0]}"

输出:

this_filename.txt

仅通过你的示例进行了测试。


请参阅:堆栈溢出正则表达式常见问题解答