I have a variable g_inboundDir which contains the value '/tmp/AI_INBOUND'.
Now, I need to read the files in the directory pointed by the variable 'g_inboundDir' and then work with the files. Directory '/tmp/AI_INBOUND' contains files a.pdf, b.pdf c.pdf etc.

NOTE: I do not want to change my current directory to '/tmp/AI_INBOUND'

I have written following code:

for i in `ls ${g_inboundDir}/*.pdf 2>/dev/null`
    j=`echo $i | sed   "s/${g_inboundDir}//"`;
    echo $j;

I was expecting echo $j will give me the file name but I am getting an error in sed command.

  • You are facing errors as g_inboundDir has slashes which are clashing with the slashes in the sed command itself. You need to escape the slashes + any other chars which might be meaningful to sed for it to work. Else, you may see my post below.
    – user218374
    Jul 9, 2017 at 19:08

2 Answers 2


You don't need to reach for sed for this:

for i in "${g_inboundDir}"/*.pdf
   echo "${i##*/}"; # will give u the filename
   # aliter:
   echo "${i}" | sed -e 's|.*/||' ;# will give the filename via sed as u wanted
  • One question I have is: What is | doing after s in the sed command 's|.*/||'
    – AlluSingh
    Jul 9, 2017 at 19:56
  • sed is bright, whatever comes AFTER the s in a sed command is used to separate search-replace. s@.*/@@ would work just as s;.*/;; or s#.*/##.
    – thecarpy
    Jul 9, 2017 at 20:01
for i in `ls ${g_inboundDir}/*.pdf 2>/dev/null`
    basename $i
  • 1
    Why parse ls? for i in ${g_inboundDir}/*.pdf would work just as well (in fact, better). Nov 29, 2019 at 14:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .