我正在使用 while 循环逐行读取文本文件,其内容是目录和文件名。我使用 basename 命令读取文件名。我想检查该文件是否存在于目录中。但下面写的代码不起作用。当我回显 basename 命令时,它会随文件名一起输出“enter”字符。我如何删除“enter”字符?
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*
textfile.txt 的内容如下
config/local/common/environment.properties
config/local/common/jmsservices.xml
config/local/common/ejbservices.xml
答案1
每man basename
:
NAME
basename - strip directory and suffix from filenames
...
-z, --zero
end each output line with NUL, not newline
如果您决定使用-z
,shell 可能会抱怨 NUL,这意味着您可能必须发送错误流至/dev/null
。
答案2
这是 的默认行为echo
。来自手册页
echo 实用程序将任何指定的操作数(以单个空格(“
') characters and followed by a newline (
\n'”)分隔)写入标准输出。
您可以指定-n
避免添加换行符:
-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.
答案3
您可以使用删除多余的输入tr
basename "$PWD" | tr -d '\n'