1

I'am reading a text file line by line using while loop whose contents are directories and file names. I read the file names using basename command. I want to check if that file exists in a directory. But the below written code does'nt work. When i echo the basename command, it is outputting an 'enter' character along with the file name. How do i remove the 'enter character' ?

while read line;do
   file=`basename "$line"`
   dir=`dirname "$line"`
   if [ -f "/data/config/${file}" ]; then
    echo "${file} is present"
   fi
done < /data/textfile.txt*

content of textfile.txt is given below

config/local/common/environment.properties
config/local/common/jmsservices.xml
config/local/common/ejbservices.xml
2
  • 1
    echo -n - Do not output the trailing newline.
    – DavidPostill
    Feb 23, 2016 at 13:24
  • Please take a look at editing-help.
    – Cyrus
    Feb 23, 2016 at 18:17

3 Answers 3

1

Per man basename:

NAME
   basename - strip directory and suffix from filenames 
...
   -z, --zero
          end each output line with NUL, not newline

If you decide to use -z, the shell might complain about the NUL, meaning you might have to send the error stream to /dev/null.

1
  • -z is a GNU specific option.
    – ramon
    Nov 11, 2018 at 12:42
0

This is the default behaviour of echo. From the man page

The echo utility writes any specified operands, separated by single blank (') characters and followed by a newline (\n') character, to the standard output.

You can specify -n to avoid the addition of the newline:

 -n    Do not print the trailing newline character.  This may also be achieved by appending `\c' to the end of the string, as is done by iBCS2 compatible systems.  Note that this option
       as well as the effect of `\c' are implementation-defined in IEEE Std 1003.1-2001 (``POSIX.1'') as amended by Cor. 1-2002.  Applications aiming for maximum portability are
       strongly encouraged to use printf(1) to suppress the newline character.
0

you can remove the extra enter using tr basename "$PWD" | tr -d '\n'

You must log in to answer this question.

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