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

标签 linux shell sed cpu-word

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

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 循环条件应该检查​​是否没有参数,如果有则继续。所以正确的形式是

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。除此之外,您可能还想保留该文件的备份,以防出现问题。
但我想这是另一个话题了。

关于linux - 如何使用shell脚本删除文件中的某些单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6331922/

相关文章:

linux - 使用带有 head 的环境变量

arrays - Bash、数组和空格的奇怪行为

unix - 从特定扩展名的所有文件中删除最后一行

bash - 如何在sed中编辑多行

linux - 如何在clearcase vob中实现 "cp -u"功能?

Linux 内核模块中冲突的头文件

php - linux - 应该是 php/modules 下的 pdo_mysql.so 文件?我只有 pdo.so 和 pdo_sqlite

xml - 如何从所有 .xml 文件中删除所有包含字符串的行?

linux - 如何将多个二进制文件通过管道传输到从标准输入读取的应用程序

linux - 我如何打印矩阵的上三角