I have multiple files inside a folder and I want to scan the contents of each file to check for a string e.g. "abc" (case sensitive). I want to output the file name as well as the string with a label like 1 or 0 to tell if the string was present or not. E.g. if there are files
A1
A2
B3
B5
C8
Z7
and only B3 and C8 contain "abc"
. The output should be as follows
A1 abc 0
A2 abc 0
B3 abc 1
B5 abc 0
C8 abc 1
Z7 abc 0
All this should be printed into a "output.txt"
file.
My code seems to work :
#!/bin/bash
touch output.txt
for f in * ;
do echo ${f} ;
echo "abc" ;
grep -w "abc" ${f}| wc -l ;
done
The output is like
A1
abc
0
A2
abc
0
B3
abc
1
B5
abc
0
C8
abc
1
Z7
abc
0
However, I am unable to print them into the txt file, also not able to do it in the order I want. Kindly advise.
Edit : I cd
into the directory containing the files and the txt
file is in an outside root directory.
Edit 2 : This is not similar to "echo -n" prints "-n" as, I want to use grep to print out file names while simultaneously adding labels depending on the presence/absence of a particular string