使用shell脚本从文件中删除特定单词

时间:2011-03-15 09:42:22

标签: shell

您好我在使用Shell脚本从文件中删除一组特定单词时遇到问题。这是我的问题,
我的档案:group.dat
样品线
管理
管理
管理员

我的脚本:groupdel.sh

#!/bin/sh
groupf="<pathtofile>/group.dat"
tmp="<pathtofile>/te"
delgrp()
{
        echo "Enter the group to be deleted"
        read gname
        echo "-------------------"
        for gn in `cat $groupf`
        do
                if [ "$gname" = "$gn" ]
                then
                        sed -e "s/$gname//g" $groupf > $tmp&&mv $tmp $groupf
                        echo "deleted group"
                        cat $groupf
                        exit 1
                fi
        done
}
echo "Welcome to Group delete wizard"
delgrp

输出: 输入要删除的组

管理

已删除的群组

ISTRATION ISTRATOR

问题:我的问题是我不希望脚本删除管理员或管理员但只删除ADMIN,任何帮助如何实现它。
在此先感谢

5 个答案:

答案 0 :(得分:2)

#!/bin/sh
groupf="<pathtofile>/group.dat"
tmp="<pathtofile>/te"
delgrp()
{
    echo "Enter the group to be deleted"
    read gname
    echo "-------------------"
    sed -e "/^$gname[[:blank:]]/d" "$groupf" > "$tmp" && mv "$tmp" "$groupf"
    echo "deleted group $gname"
    cat "$groupf"
    return 0
}
echo "Welcome to Group delete wizard"
delgrp

假设组名在行的开头,并且行上还有其他内容,并且您想要删除整行,请使用正则表达式和命令,如图所示。

不需要循环,因为sed将免费迭代文件行。

你应该从一个函数return而不是exit。零意味着成功。一个表示错误或失败。

始终引用包含文件名的变量名称。

答案 1 :(得分:0)

如果单词正确分隔,您可以使用\W来表示单词的开头和结尾:

sed -e "s/\(\W\)$gname\(\W\)/\1\2/g" $groupf > $tmp&&mv $tmp $groupf

答案 2 :(得分:0)

如果文件是每个行的一个组,并且组名是该行的唯一内容,请在正则表达式中使用锚点:

s/^$gname:.*//g

如果你安装了Perl,你可以用这样的东西简化一下这个:

if grep -q "^${gname}:" $groupf ; then
    perl -ni -e "print unless /^${gname}:/" $groupf
    echo "Group deleted."
else
    echo "No such group $gname."
fi

甚至

grep -v "^${gname}:" $groupf > $tmp && \
    cp -f $tmp $groupf && rm -f $tmp

之外的所有行复制到临时文件中,然后将tempfile复制到原始文件上,替换它。

请注意,我建议使用cp而不是mv来保留原始文件的权限; mv将导致已编辑的文件具有根据您的umask设置的权限,而不考虑原始权限。

所以,对于完整的脚本:

#!/bin/sh
groupf="<pathtofile>/group.dat"
tmp="<pathtofile>/te"
delgrp()
{
    echo -n "Enter the group to be deleted: "
    read gname
    echo "-------------------"
    if grep -q "^${gname}:" $groupf ; then
        grep -v "^${gname}:" $groupf > $tmp
        cp -f $tmp $groupf
        rm -f $tmp
    else
        echo "No such group '$gname'"
    fi
}
echo "Welcome to Group delete wizard"
delgrp

这应该可靠地运作。

答案 3 :(得分:0)

Awk是sed的可读替代品:

awk -v to_delete="$gname" -F: '$1 == to_delete {next} {print}'

答案 4 :(得分:-1)

为什么不使用sed?

sed 's/^word$//g' 

您也可以使用正则表达式指定多个单词

sed 's/word1|word2//g'

我没试过,但这就是你需要的。只需在Internet上查看sed语法。

此致