在Shell中读取文件,一次一行进行处理。用for处理起来比较简单,但是如果一行中有空格分隔的话,那么处理起来如果把一行作为一个参数,用for就不行了,变通一下的做法有很多中,比如用awk。昨天在处理这个问题花了一点时间研究了一下shell读取文件的方法,如下:
#!/bin/ksh
cat file1 | while read line
do
line2=`echo $line | sed ‘s//*////*/g’ `
# echo "$line2"
grep "$line2" file2 > /dev/null
a=$?
grep "$line2" file3 >/dev/null
b=$?
# echo "a=$a,b=$b"
if [[ $a == 0 ]] && [[ $b == 0 ]]
then
echo $line
fi
done
ricky@ricky-desktop:~$
这个脚本是用来实现如下的需求:
1)比较三个文件中相同的部分,输出
2)每个文件中的内容中有些特殊字符,在grep的时候需要进行特殊处理,用sed进行了替换
3)因为文件内容中有空格,所以读取的时候不能用传统的for x in a b c的方法
文件内容大致如下:
ricky@ricky-desktop:~$
more file1
line1 32* 256 megabyte (s )
line2 32* 256 megabyte (s )
line3 32* 256 megabyte (s )
line1 32* 256 megabyte (s )
line2 32* 256 megabyte (s )
line3 32* 256 megabyte (s )