编写一个shell程序convert.sh
如果输入convert.sh *.c,并且该c程序是一个普通文件,那么生成一个新的文件*.txt,该文件为c源程序文件每行加上行数,行号后面加一个tab空格,例如:¥convert.sh nihao.c生成nihao.txt
nihao.c内容为:
#include《stdio.h》
main()
{
printf("nihao");
}
生成的nihao.txt的内容为:
1 #include《stdio.h》
2 main()
3 {
4 printf("nihao");
5 }
如果输入的文件扩展名不是 c ,或不是普通文件,或没有输入参数,则给出该shell程序的用法
画出程序流程图
这道题目挺好,涉及了判断表达式,字符串截取,格式化输出。
convert.sh 内容如下:
#!/bin/bash
guide="Usage: `basename $0` *.c"
if [ $# -eq 0 ]; then # no input parameter
echo "$guide"
exit 1
fi
file="$1"
ext=${file##*.} # parse file extension
name=${file%.*} # parse basic file name
# file doesn't exist or is not a regular file, or is not a C source file
if [ ! -f $file -o $ext != "c" ]; then
echo "Please check if $file is a valid file!"
echo "$guide"
exit 1
fi
awk '{printf("%d\t%s\n",++i,$0)}' $file >${name}.txt
exit 0
convert.sh 内容如下:
#!/bin/bash
guide="Usage: `basename $0` *.c"
if [ $# -eq 0 ]; then # no input parameter
echo "$guide"
exit 1
fi
file="$1"
ext=${file##*.} # parse file extension
name=${file%.*} # parse basic file name
# file doesn't exist or is not a regular file, or is not a C source file
if [ ! -f $file -o $ext != "c" ]; then
echo "Please check if $file is a valid file!"
echo "$guide"
exit 1
fi
awk '{printf("%d\t%s\n",++i,$0)}' $file >${name}.txt
exit 0
温馨提示:答案为网友推荐,仅供参考
第1个回答 2011-09-22
这个普通文件 和 源码文件是怎么区分的。。什么叫C程序的普通文件。
[test@myhost ~]$ cat -n nihao.c > nihao.txt
[test@myhost ~]$ more nihao.txt
1 #include《stdio.h》
2 main()
3 {
4 printf("nihao");
5 }
看来是我想的肤浅了。
[test@myhost ~]$ cat -n nihao.c > nihao.txt
[test@myhost ~]$ more nihao.txt
1 #include《stdio.h》
2 main()
3 {
4 printf("nihao");
5 }
看来是我想的肤浅了。
第2个回答 2011-09-22
saddad追问
急求,如果您会,麻烦您指导下,如果您不知道,请不要添乱了