0

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
3
  • Which part works and which not? Commented Jun 8, 2020 at 18:41
  • @Cyrus I am not getting anything for mdlocation="${file}" echo ${mdlocation} Commented Jun 8, 2020 at 18:52
  • you can use echo `realpath ${file}` to get absolute path for first case. Commented Jun 8, 2020 at 19:42

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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

2 Comments

echo `realpath ${file}` Is a useless use of echo. Why not echo $(echo $(echo $(realpath $file)))? Just realpath $file. Please do not use ` backticks - use $(...) instead.
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.