5

File: test.zip

Bash script

while read filename; do
zip_file=${filename}
# do stuff    
done; 

Value stored in variable = "test"

4

Use bash parameter expansion:

zip_file="${filename}"
new_name="${zip_file%.*}"   
  • new_name will contain the name test if the zip_file has test.zip

  • If the zip_file has test.foo.zip, new_name will have test.foo, if you want only test out of test.foo.zip use:

    new_name="${zip_file%%.*}"
    
  • This seems to include part of the path. I just want the file name. eg NOT ./Somefolder/Somefolder/FilenameminusExtn but FilenameminusExtn – JohnnyBizzle May 24 '15 at 14:39
  • @JohnnyBizzle With due respect why would you give the filename as test.zip, why don't you include the path or mention that there would be path before the file name? Please edit your question and add some examples (be precise) and your desired output (be precise).. – heemayl May 24 '15 at 14:42
  • I think you just need $(basename "${zip_file}") to get what I want. – JohnnyBizzle May 24 '15 at 15:34
  • @JohnnyBizzle no, you would need $(basename "${zipfile}" .zip) to get what you want. – muru May 24 '15 at 16:42
1

heemayl is still right: example:

full_path=/foo/bar/baz.zip
file_name="${full_path##*/}"
name="${file_name%.*}"
0

Using sed:

zip_file="$(<<< "${filename}" sed -r 's/^(.*)\..*/\1/')"
  • zip_file="$( [...] )": assigns the stdout of an invoked subshell to the variable zip_file as a string
  • <<< "${filename}" [...]: redirects the content of the variable ${filename} to the invoked subshell's stdin as a string
  • sed -r 's/^(.*)\./\1/': edits the content of the invoked subshell's stdin using extended regular expressions, by matching the whole string and replacing it with the substring matching every character from the start until the last dot

Edit: Having seen your comment to heemayl's answer, to replace with the substring matching every character from the last slash to the last dot:

zip_file="$(<<< "${filename}" sed -r 's/^.*\/(.*)\..*/\1/')"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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