我想逐字阅读文本文件。问题:有些词包含“/*”。这样的词导致脚本返回根目录中的文件。我试过:
for word in $(< file)
do
printf "[%s]\n" "$word"
done
以及与 echo/cat/etc 的其他几种组合......对于这个文件:
/* example file
我得到以下输出:
[/bin]
[/cygdrive]
[/Cygwin.bat]
...
[example]
[file]
应该很容易,但它让我发疯。
您需要关闭路径名扩展通配符。运行一个新的shell,bash -f然后重试。请参阅http://wiki.bash-hackers.org/syntax/expansion/globsman bash或使用,也许可以进入手册页man bash | col -b >bash.txt。
这个解决方案怎么样,周围的双引号$(< file)停止*被扩展并sed用于根据需要格式化输出:
for word in "$(< file)"
do
echo "$word" | sed -E 's/(\S*)(\s)/[\1]\2\n/g'
done
输出:
[/*]
[example]
[file]
这可能会有所帮助;
# skip blank lines and comment lines begining with hash (#)
cat $CONFIG_FILE | while read LINE
do
first_char=`echo $LINE | cut -c1-1`
if [ "${first_char}" = "#" ]
then
echo "Skip line with first_char= >>${first_char}<<"
else
:
echo "process line: $LINE" ;
fi
done
另一种方法是使用 case 语句
这个怎么样?
while read -a a; do printf '[%s]\n' "${a[@]}"; done < file
输出:
[/*]
[example]
[file]