0

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`
do
    j=`echo $i | sed   "s/${g_inboundDir}//"`;
    echo $j;
done;

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 '17 at 19:08
3

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

for i in "${g_inboundDir}"/*.pdf
do
   echo "${i##*/}"; # will give u the filename
   # aliter:
   echo "${i}" | sed -e 's|.*/||' ;# will give the filename via sed as u wanted
done
  • One question I have is: What is | doing after s in the sed command 's|.*/||' – AlluSingh Jul 9 '17 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 '17 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.