如果在另一个文件中出现,如何写入新文件?

如果在另一个文件中出现,如何写入新文件?

我需要根据另一个文件中找到的事件创建并写入一个新文件。 IE:

Occurrence found in first file
then write same Occurrence in another one/new

更具体:

“File1”:查找出现次数:

Occurrence1
Occurrence2
OccurrenceN

##If the `Occurence1` is find in `File1` then write in the `new file` the same Occurrence

我有下一个功能命令来ksh指定文件中出现的次数以及不出现的次数:

users=(Occurrence1 Occurrence2 Occurrence3 Occurrence4 ... OccurrenceN)
for i in "${users[@]}"
do
grep -qw $i file1 && echo "$i is in the file" || echo "$i is not in the file"
done

我对早期的代码做了一些修改:

users=(Occurrence1 Occurrence2 Occurrence3 ... OccurrenceN)
for i in "${users[@]}"
do
        grep -qw $i File1.txt && echo "$i is in the file" || echo "$i is not in the file"
       if [[ $user = "*is in the file" ]]; then
       echo $user >> users_in_file.txt
       elif [[ $user = "*is not in the file" ]]; then
       echo $user >> users_not_in_file.txt
       fi
done

我有想法执行最后一个命令来实现我的目标,但不起作用。还有另外一个可以做吗?提前致谢。有任何疑问请留言评论。

答案1

您可以grep直接使用作为 的条件if,并进行相应操作:

users=(Occurrence1 Occurrence2 Occurrence13  OccurrenceN)
for i in "${users[@]}"
do
       if grep -qw "$i" File1.txt; then
                echo "$i is in the file"
                echo "$i" >> users_in_file.txt
       else
                echo "$i is not in the file"
                echo "$i" >> users_not_in_file.txt
       fi
done

相关内容