colebod209
colebod209

Reputation: 127

Finding a file extension in a string using shell script

I have a long string, which contains a filename somewhere in it. I want to return just the filename.

How can I do this in a shell script, i.e. using sed, awk etc?

The following works in python, but I need it to work in a shell script.

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

EDIT adding shell script requirement

I would call shell script like this:

./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

Upvotes: 2

Views: 156

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133680

Considering that you want to get file name with extension and then check if file is present or not in system, if this is the case could you please try following. Adding an additional check which is checking if 2 arguments are NOT passed to script then exit from program.

cat script.bash
if [[ "$#" -ne 2 ]]
then
    echo "Please do enter do arguments as per script's need, exiting from program now."
    exit 1;
fi

fileName=$(echo "$1" | awk -v ext="$2" 'match($0,/\/[^ :]*/){print substr($0,RSTART,RLENGTH) ext}')
echo "File name with file extension is: $fileName"


if [[ -f "$fileName" ]]
then
    echo "File $fileName is present"
else
    echo "File $fileName is NOT present."
fi

Upvotes: 2

Cyrus
Cyrus

Reputation: 88829

With bash and a regex:

#!/bin/bash

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

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

Output:

this_filename.txt

Tested only with your example.


See: The Stack Overflow Regular Expressions FAQ

Upvotes: 2

Related Questions