繁体   English   中英

如何使用 shell 脚本从文件中删除某些单词?

[英]How to delete certain words from files with shell script?

我必须从通过命令行作为参数给出的每个文件中删除包含至少一个数字的每个单词。 这是我的代码:

while [ "$*" != "" ]; do
    if [ ! -f $1 ]
        then echo "$1 not file"
    else
        sed -ie  "s/[^ ]*[0-9][^ ]*//g" $1
    fi
    shift
done

如果我只有一个文件,它会完美运行,但如果我有更多文件,它会为每个文件提供相同的结果。 在每个文件中运行脚本后,将得到第一个文件的结果。

有人可以告诉我我错过了什么吗?

编辑2:

这就是我现在正在运行的:

while [ "$#" -ne 0 ]; do
for file in "$@"; do
    if [ ! -e "$file" ]; then
        printf "file doesn't exist: %s\n" "$file"
        continue;
    fi
    if [ ! -f "$file" ]; then
        printf "not a file: %s\n" "$file"
        continue;
    fi
done
    sed -i "s/[^ ]*[0-9][^ ]*//g" "$file"
done

我说的是 while 循环的 done 和 for 循环的 done; 但即使没有,我的脚本也会继续运行。

编辑:

基本上是一样的,只是有点不同。 我必须从每个文件的每一行中删除第二个和第四个单词(单词仅包含字母数字字符)。 它工作不正常,我找不到错误。 这是我的代码:

while [ "$*" != "" ]; do
    if [ ! -f $1 ]
        then echo "$1 not file"
    else
        sed -ie  's/^\( *[^ ]+\) +[^ ]+\(.*\)/\1\2/
                  s/^\( *[^ ]+\)\( +[^ ]+\) +[^ ]+\(.*\)/\1\2\3/g' $1
    fi
    shift
done

while 循环条件应检查是否没有 arguments,如果有则应继续。 所以正确的形式是

while [ "$#" -ne 0 ]; do

现在,您真正想要的是获取每个参数并对其进行处理。 这自动意味着一个for 循环 所以你真正应该做的是

for file in $@; do

现在,一个文件中可以有空格,因此获取该文件名并检查它是否真的是一个文件应该被引用,并且您还应该首先检查是否存在

for file in "$@"; do
    if [ ! -e "$file" ]; then
        printf "file doesn't exist: %s\n" "$file"
        continue;
    fi
    if [ ! -f "$file" ]; then
        printf "not a file: %s\n" "$file"
        continue;
    fi
    sed -i "s/[^ ]*[0-9][^ ]*//g" "$file"
done

我可以在sed上进行更多扩展,其中-i开关仅限于 GNU sed。 除此之外,您可能还希望保留该文件的备份,以防出现问题。
但我猜这是另一个话题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM