Home > Enterprise >  shell script for loop printing file names complete path
shell script for loop printing file names complete path

Time:09-30

Im using below shell scripts,

    INBOX=/home/tmp/
    for fileName in $INBOX"abc*.csv"
    do
        echo $fileName
    done

    **output:**
       /home/tmp/abc1.csv
       /home/tmp/abc2.csv
    
    **Expected output:**
    abc1.csv
    abc2.csv

it is printing files with whole path. But I need only file name alone.

Thanks

CodePudding user response:

INBOX=/home/tmp/
for fileName in $INBOX"abc*.csv"
do
     echo $(basename $fileName)
done 


  

CodePudding user response:

You have two primary problems preventing the output you want:

  1. You have enclosed the '*' within double-quotes which will result in all your filenames being part of a single string separated by the first character of your internal field separator;
  2. You need to trim the leading /home/tmp/ from the resulting filename which you can do with Parameter Expansion with Substring Removal of the form ${filename##*/}. (which will trim characters from the front of filename through the last included '/')

You can put that together in your script as:

#!/bin/sh

INBOX=/home/tmp/
for fileName in "$INBOX"abc*.csv
do
    echo "${fileName##*/}"
done
  • Related