0

I am currently learning how to use grep awk sed. I am encountering an issue with a variable that has the value of the following: new_file="main_folder/test.txt". Practically a directory with a file inside. I am able to initially use sed to remove the file extension. But the main goal is to just get the file name test(no extension) extracted from the variable new_file. How could I remove everything to the last and the file extension?

So far all that i have working is removing extension

new_file=`rev <<< "$new_file" | cut -d"." -f2- | rev`

Example:

Input

new_file="parent_folder/child_folder/file_name.txt"
new_file2="parent_folder/child_folder/sub_child_folder/file_name2.txt"

Desired Output:

file_name
file_name2
1
  • Regexps are your friends. Try matching any character followed by a '/'. This would match all the dir/ subdir/ parts which can then be removed.
    – JoErNanO
    Oct 9, 2014 at 23:57

2 Answers 2

1

You can use the basename utility.

$ new_file="parent_folder/child_folder/file_name.txt"
$ x=$(basename "$new_file" .txt)
$ echo "$x"
file_name

or your case

new_file=`basename $new_file | cut -d "." --complement -f2-`
2
  • how could I assign the value of basename $new_file to another variable? Oct 10, 2014 at 0:01
  • True, basename can only strip the extension if you know the exact extension.
    – chepner
    Oct 10, 2014 at 0:06
1

Through sed,

$ new_file="parent_folder/child_folder/file_name.txt"
$ new_file2="parent_folder/child_folder/sub_child_folder/file_name2.txt"
$ sed 's~.*/\([^/.]*\)\..*$~\1~' <<< "$new_file"
file_name
$ sed 's~.*/\([^/.]*\)\..*$~\1~' <<< "$new_file2"
file_name2

To assign the value to another variable,

$ foo=$(sed 's~.*/\([^/.]*\)\..*$~\1~' <<< "$new_file2")
$ echo "$foo"
file_name2

Simply you could try this sed command.

$ sed 's~.*/\(.*\)\..*$~\1~' <<< "$new_file2"
file_name2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.