Reputation: 663
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
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
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[@]}"
Upvotes: 0
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