2

背景:我在 script_testing 下的单字母目录中有一堆名为 username.sub 的文件名(用户名的第一个字母是文件夹名称)。对于每个 username.sub,我需要检查行 user.$username.contacts 是否存在,如果不存在,则附加该行,后跟一个真正的选项卡。

问题:鉴于我在下面的代码,为什么它没有附加到文件中?我想我错过了一些简单的东西。即使该行不存在,我也会不断收到“已订阅的联系人”。

#!/bin/bash
 Path_to_files=/home/user/script_testing/^[A-z]+$/
 FULLNAME="${Path_to_files##*/}"
 NAME="${FULLNAME%.*}"
 if grep 'contacts' $NAME.sub; then
   echo 'contacts already subscribed'
else
    echo "subscribing to contacts"
    echo -e user.$NAME.Contacts \t >> $NAME.sub
fi
4

2 回答 2

1

您正在寻找这个词contacts- 根据您在这些文件中的其他内容,它可能始终存在。

相反,用于grep -q "^user\.$NAME\.Contacts"查找您的线路。

于 2013-06-10T19:54:55.117 回答
1

修复了以下内容:

#!/bin/bash
#testing directory
#p=$HOME/script_testing
for f in "$p"/*/*.sub ; do
# if this is a file
 if [ -f "$f" ]; then
# define variables
F="${f##*/}"
u="${F%%.*}"
cont=$(grep "user.$u.Contacts" "$f")
cal=$(grep "user.$u.Calendar" "$f")
# if our file doesn't contain Contacts subscription
if [ -z "$cont" ]; then
 # add Contacts subscription
 echo -e "user.$u.Contacts\t" >> "$f"
#fi
# if our file doesn't contain Calendar subscription
elif [ -z "$cal" ]; then
 # add Calendar subscription
 echo -e "user.$u.Calendar\t" >> "$f"
fi
fi
done

还添加了额外的行来追加。请让我知道这是否有问题,以便我学习,但我没有遇到任何问题。

于 2013-06-12T16:25:46.580 回答