Yamuna_dhungana
Yamuna_dhungana

Reputation: 663

How to extract different variations of file name in bash

Say I have these files in my folder below mydir

file1.txt
file2.txt
file3.txt
file4.txt.mdgg

I want to get file name with full path, file name only and file name without path and .txt extension. For this I tried, but doesn't seem to work. Can someone please suggest me what is wrong with my code?

mydir="/home/path"



for file in "${mydir}/"*.txt; do
    # full path to txt
    mdlocation="${file}"
    echo ${mdlocation}
    #file name of txt (without path)
    filename="$(basename -- "$file")"
    echo ${filename}
    #file name of txt file (without path and .txt extension)
    base="$(echo "$filename" | cut -f 1 -d '.')"
    echo ${base}
done

Upvotes: 0

Views: 125

Answers (3)

Ladislav Rolnik
Ladislav Rolnik

Reputation: 176

for file in *.txt; do
# full path to txt
realpath ${file}
#file name of txt (without path)
echo ${file}
#file name of txt file (without path and .txt extension)
base="$(echo "$file" | cut -f 1 -d '.')"
echo ${base}
done

Upvotes: 0

Jetchisel
Jetchisel

Reputation: 7821

An alternative is to use arrays, and P.E. parameter expansion, without any external tools/utility from the shell.

#!/usr/bin/env bash

mydir=/home/path

files=("$mydir/"*.txt)


filenames=("${files[@]##*/}")
pathnames=("${files[@]%/*}")
filenames_no_ext=("${filenames[@]%.txt}")

printf '%s\n' "${pathnames[@]}"
printf '%s\n' "${filenames[@]}"
printf '%s\n' "${filenames_no_ext[@]}"
  • If you need to loop through the arrays, to do some other things, then do so, since arrays are iterable.

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15388

In bash, assuming $mydir is a full path,

for file in "$mydir/"*.txt    # full path to each txt
do echo "$file"                
   filename="${file##*/}"     # file name without path
   echo "${filename}"
   base="${filename%.txt}"    # file name without path or .txt extension
   echo "${base}"
done

c.f. https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Upvotes: 1

Related Questions