Hi

I know the cut option which is used to cut the column from file. I like to get the filename only when it is being stored in the variable with the extension attached to.

file=jasmine.txt

I like to fetch jasmine(file name only). I am newbie to shell scripting. Please help me.

Jasmine

Dani AI

Generated

Both and are right — awk/sed will do the job. For a simple, faster, and more idiomatic shell solution you can use parameter expansion (no external commands spawned). It handles plain variables and works well with paths.

file="/path/to/jasmine.txt"
name="${file##*/}"    # strip any directory path -> jasmine.txt
base="${name%.*}"     # strip the last extension        -> jasmine
printf '%s\n' "$base"

${var##*/} removes everything up to the last slash (gives the basename). ${var%.*} removes the shortest match of a dot-plus-suffix from the end (drops the final extension). Use ${var%%.*} if you need everything before the first dot instead (different behavior for files with multiple dots).

A couple of practical notes:

  • Quote variables to handle spaces: file="my file.txt" and use "$base" when printing.
  • Hidden files like .bashrc become empty after ${name%.*}. A simple guard fixes that:
name=${file##*/}
base=${name%.*}
[ -z "$base" ] && base="$name"
printf '%s\n' "$base"

Parameter expansion is POSIX-compliant and works in sh/bash/ksh/dash; it’s generally preferable to spawning awk/sed for simple filename manipulations.

Recommended Answers

All 2 Replies

If there will always be only one "." as in filename.txt then given
var=filename.txt
you can do
var2=`echo $var | awk -F'.' '{print $1}'`

if there is any possibility that the filename will have more than one "." as in filename.date.txt
then given
var=filename.date.txt
you can do
var2=`echo $var | sed -e 's/\.[^\.]*$//'`
this will return filename.date

Thank u very much.It is working fine.

I used this one var2=`echo $var | awk -F. '{print $1}'`

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.