【问题标题】:"while read line" giving garbage data while reading a C file [duplicate]“读取行时”在读取 C 文件时提供垃圾数据 [重复]
【发布时间】:2016-10-04 16:54:42
【问题描述】:

我想编写一个使用 shell 脚本解析 C 文件的所有 cmets 的小脚本,但我什至没有得到正确的读取 o/p,我得到的文件 o/p 与其他垃圾数据混合在一起。

>/.1432804547.3007 /.1432804567.3007 /.1432804587.3007 /.1432804608.4021 /.1432804628.4021 /.1432804648.4021 /.1432804668.4021 /.1432804688.4021 /bin >/boot /dev /etc /home /lib /lib64 /lost+found /media /misc /mnt /net /opt /proc >/root /sbin /selinux /srv /sys /tmp /usr /var
>parsed_comments.tmp parse_func.sh file_update_time - update mtime and ctime time
>parsed_comments.tmp parse_func.sh @file: file accessed
>parsed_comments.tmp parse_func.sh
>parsed_comments.tmp parse_func.sh Update the mtime and ctime members of an inode and mark the inode
>parsed_comments.tmp parse_func.sh for writeback. Note that this function is meant exclusively for
>parsed_comments.tmp parse_func.sh usage in the file write path of filesystems, and filesystems may
>parsed_comments.tmp parse_func.sh choose to explicitly ignore update via this function with the
>parsed_comments.tmp parse_func.sh S_NOCMTIME inode flag, e.g. for network filesystem where these
>parsed_comments.tmp parse_func.sh timestamps are handled by the server.
>*/
>void file_update_time(struct file *file)

这就是我正在做的事情..

   parse_comments() {
    local filename="$1"
    while read line; do
    echo $line | grep "*"
    done < "$filename"
    parse_comments "/root/rpmbuild/linux-2.6.32-431.17.1.el6.x86_64/fs/inode.c"

我已经尝试了所有解决方案(比如 - while read -r、while read -u 3 和其他),因为 while read 问题没有一个解决方案对我有用。 我不知道用while循环读取有什么问题请帮助... 如果我将 'awk' 用于相同的工作,它可以正常工作。但是“awk”不能满足我的目的。

【问题讨论】:

  • 如果你正在写一个关于卖鸡蛋的程序,你会用 eggs 标签来询问它吗?
  • 通过shellcheck.net 运行它并修复它报告的错误,然后再从这里开始。
  • 我不确定第一个代码块应该代表什么。那是输出,还是您尝试运行的内容,还是输入文件的内容...?
  • @trentcl,输出非常可信。由于缺少引用,每个/* 都将扩展为根文件系统 f'rinstance 中的文件列表。
  • ...无论如何,这并没有描述所需的行为(OP 实际想要完成的事情 - 为什么不能只是 fgrep -e '*' inode.c?),所以它失败了满足stackoverflow.com/help/mcve的标准

标签: linux bash shell


【解决方案1】:

问题在shellcheck.net 上得到解决。这是修改后的代码...

parse_comments() {
    local filename="$1"
    while read -r line; do
    echo "$line" | fgrep -e "*" 
    done < "$filename"
}
parse_comments "/root/rpmbuild/linux-2.6.32-431.17.1.el6.x86_64/fs/inode.c"

【讨论】:

  • 为什么你有while read循环,而不是在整个文件上运行一次fgrep?也就是说,写parse_comments() { fgrep -e '*' &lt;"$1"; } 会更有效率——如果你在实践中计时,你会发现它在大文件上的运行速度明显快于当前方法。
  • @CharlesDuffy:其实这只是我工作的开始。我必须在 while 循环中做很多其他事情,这就是我使用它的原因。但偏离路线的表现也是关键因素,我会根据你的建议工作。非常感谢您的建议。
  • 即使您需要对结果执行其他操作,每行调用一个 grep 仍然是不可原谅的开销。您可以使用[[ $line =~ '*' ]] 更快地检查一行是否包含文字星号,或者您可以将&lt; "$filename" 替换为&lt; &lt;(fgrep -e '*' "$filename") 以使循环仅遍历grep 的输出。
  • @CharlesDuffy:是的,替换看起来很酷,感谢您的持续建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多