List all file names that contain two specific words.


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting List all file names that contain two specific words.
# 8  
Old 06-12-2010
This perhaps?
Code:
grep -rlm1 'B' $(grep -rlm1 'A' . )



---------- Post updated at 20:07 ---------- Previous update was at 19:58 ----------

To tackle names with spaces, perhaps this:
Code:
grep -rlm1 'B' . | sed 's/\(^\|$\)/"/g' | xargs -n1 grep -rlm1 'A'

# 9  
Old 06-12-2010
Quote:
Originally Posted by dr.house
You're right ... therefore, (my) second attempt:

Code:
grep -r 'A' . | grep 'B' -

If a filename that matched 'A' contains 'B', that would lead to a false positive.

Apologies if it seems that I'm busting chops. Smilie

One possible approach:
Code:
#!/bin/sh

find . -type f -exec sh -c '
    for f; do
        grep -q '\'"$1"\'' "$f" && grep -q '\'"$2"\'' "$f" && echo "$f"
    done' sh {} +

Regards,
Alister
# 10  
Old 06-12-2010
Hi.

Appropriate versions of find are very flexible:
Code:
#!/usr/bin/env bash

# @(#) s1	Demonstrate finding filenames containing two specific characters.

# Uncomment to run script as external user.
# export PATH="/usr/local/bin:/usr/bin:/bin"
# Infrastructure details, environment, commands for forum posts. 
set +o nounset
pe() { for i;do printf "%s" "$i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe ; pe "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
pe "(Versions displayed with local utility \"version\")"
c=$( ps | grep $$ | awk '{print $NF}' )
version >/dev/null 2>&1 && s=$(_eat $0 $1) || s=""
[ "$c" = "$s" ] && p="$s" || p="$c"
version >/dev/null 2>&1 && version "=o" $p find
set -o nounset

# Remove, create files.

LIST="AB BA 1A2B3 4B5A6 A7 B8"
for i in $LIST
do
  rm -f "$i"
  touch "$i"
done

pl " Files containing \"A\" or \"B\":"
ls *[A-Z]*

pl " Results of finding A and B in filename:"
find . -regextype posix-extended -regex '.*((A.*B)|(B.*A)).*'

exit 0

producing:
Code:
% ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0 
GNU bash 3.2.39
find (GNU findutils) 4.4.0

-----
 Files containing "A" or "B":
1A2B3  4B5A6  A7  AB  B8  BA

-----
 Results of finding A and B in filename:
./BA
./AB
./1A2B3
./4B5A6

See man pages for details ... cheers, drl
# 11  
Old 06-12-2010
Quote:
Originally Posted by drl
Hi.

Appropriate versions of find are very flexible:
Code:
find . -regextype posix-extended -regex '.*((A.*B)|(B.*A)).*'

You really don't need to resort to non-standard extensions for this situation, though. The following will accomplish a similar task while using only standardized primaries:
Code:
find . -name '*A*' -name '*B*'

I said "similar" because your approach, -regex, matches against the entire path, while -name only matches against the base name (which may be preferable).

However, I interpreted the original poster's problem statement differently. I took it to mean that the two words/characters being searched for are not in the filename but in the file's contents.

Regards,
Alister

Last edited by alister; 06-12-2010 at 07:59 PM..
# 12  
Old 06-12-2010
Hi.

Observations:

1) alister is quite right. His expression will indeed do the same as mine (if within the entire path). It may be useful to know that GNU find shares aspects of regular expressions with the grep family.

2) Misinterpretation is best avoided by the questioner providing examples.

Best wishes ... cheers, drl

---------- Post updated at 18:46 ---------- Previous update was at 18:24 ----------

Hi.

If we are looking at the contents of the files, then my preference is to look at the content only once. Here's a script that does that. It uses a command that is available in Debian repositories.
Code:
#!/usr/bin/env bash

# @(#) s3	Demonstrate finding files containing two specific characters.
# See: http://www.incava.org/projects/glark/

# Uncomment to run script as external user.
# export PATH="/usr/local/bin:/usr/bin:/bin"
# Infrastructure details, environment, commands for forum posts. 
set +o nounset
pe() { for i;do printf "%s" "$i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe ; pe "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
pe "(Versions displayed with local utility \"version\")"
c=$( ps | grep $$ | awk '{print $NF}' )
version >/dev/null 2>&1 && s=$(_eat $0 $1) || s=""
[ "$c" = "$s" ] && p="$s" || p="$c"
version >/dev/null 2>&1 && version "=o" $p find glark
set -o nounset

# Sample data files, using head & tail as a last resort.
pl " Files containing data \"A\" or \"B\":"
pe
specimen t* \
|| { pe "(head/tail)"; head -n 5 t*; pe " ||"; tail -n 5 t*; }

pl " Results of finding A and B contained in files, glark:"
find . -type f |
egrep -v '[sr]' |	# don't look at scripts
xargs glark -l --and=-1 "A" "B" --end-of-and

exit 0

producing:
Code:
% ./s3

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0 
GNU bash 3.2.39
find (GNU findutils) 4.4.0
glark, version 1.8.0

-----
 Files containing data "A" or "B":

Whole: 5:0:5 of 3 lines in file "t1"
A
1
B

Whole: 5:0:5 of 3 lines in file "t2"
B
2
A

Whole: 5:0:5 of 1 lines in file "t3"
AB

Whole: 5:0:5 of 1 lines in file "t4"
BA

Whole: 5:0:5 of 2 lines in file "t5"
A
b

Whole: 5:0:5 of 2 lines in file "t6"
a
B

-----
 Results of finding A and B contained in files, glark:
./t4
./t3
./t2
./t1

If glark is not available to your package manager, see the URL in the script ... cheers, drl
# 13  
Old 06-13-2010
Quote:
Originally Posted by alister
If a filename that matched 'A' contains 'B', that would lead to a false positive.

Apologies if it seems that I'm busting chops. Smilie
If what I propose leads to incorrect results, then I'm wrong. (No offense taken.)
# 14  
Old 06-13-2010
MySQL

Quote:
Originally Posted by alister
None of these proposals are correct; files containing either word but not both will match.

Regards,
Alister
Allright Smilie

Code:
[root@rhnserver test2]# cat a
A Bdsadadasdas C
Adasdas dasdasdasdB Cdsqdasdasd
a adasdasdasdaskl;
dwqewdqwodkwowe
asdpdkpoakoapsdadas dasdsd
A B Cdasdasdas
Adsadasda dasdasB C dasd asdas
Adsadas Bdasdasd Cdasdasdas
Adasdas B Casdasd

Code:
[root@rhnserver test2]# cat b
ABBB BBA A BC
232432423 5r345435

Code:
[root@rhnserver test2]# cat c
asasa A scascas BX
  A asodja;sdwedwkdk[dk[wedfwe[fkc  f
      B asasasqsqwe

Code:
 
[root@rhnserver test2]# ./findd
./a file contains A and B word..
./c file contains A and B word..

Code:
#!/bin/bash
oIFS=$IFS
rm -f filelst
find . ! \( -name "*bak1" -o -name "findd" -o -name "filelst" \) !  -type d -print | xargs -L 1 file | sed -n '/ASCII/p' >> filelst
for i in $( (cut -d: -f1 filelst) )
    do
# for backup orj files
cp $i ${i}_bak1
# change in file for
sed -i 's/  */-/g' $i
    done
Ax=0;Bx=0
i=1
rline=0
for files in `cat filelst | cut -d: -f1`
 do
  ((i++))
  ((rline++))
 while read -r line
  do
    c=$( (echo $line | grep -o "-" | wc -l) )
    ((c++))
    rfile=$( (cut -d: -f1 filelst | sed -n $rline"p") )
IFS="-"
chargr=("")
chargr=( $line )
#eval read -r wrd{1..$c} <<< $line
if [[ ! $Ax = 1 || ! $Bx = 1 ]] ; then
 for wrdx in ${chargr[@]}
  do
    if [ "$wrdx" = "A" ] ; then
  Ax=1
    fi
     if [ "$wrdx" = "B" ] ; then
  Bx=1
     fi
  done
fi
    c=0
  done < $files
 
 if [[ $Ax = 1 && $Bx = 1 ]] ; then
      echo $rfile file contains A and B word..
 fi
Ax=0;Bx=0
 
 done
iIFS=$oIFS
# if you files to orj state as last use another script
cat filelst | sed 's/:.*//' | while read mv; do mv -f ${mv}_bak1 $mv; done

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How to replace some specific words from file?

I have the file like this. cat 123.txt <p> <table border='1' width='90%' align='center' summary='Script output'> <tr><td>text </td> </tr> </table> </p> I want to replace some tags and want the output like below. I tried with awk & sed commands. But no luck. Could someone help me on this? ... (4 Replies)
Discussion started by: thomasraj87
4 Replies

2. UNIX for Advanced & Expert Users

List all file names that contain two specific words. ( follow up )

Being new to the forum, I tried finding a solution to find files containing 2 words not necessarily on the same line. This thread "List all file names that contain two specific words." answered it in part, but I was looking for a more concise solution. Here's a one-line suggestion... (8 Replies)
Discussion started by: Symbo53
8 Replies

3. UNIX for Beginners Questions & Answers

Non-root script used search and list specific key words

Hy there all. Im new here. Olso new to terminal & bash, but it seams that for me it's much easyer to undarsatnd scripts than an actual programming language as c or anyother languare for that matter. S-o here is one og my home works s-o to speak. Write a shell script which: -only works as a... (1 Reply)
Discussion started by: Crisso2Face
1 Replies

4. Shell Programming and Scripting

find specific file names and execute a command depending on file's name

Hi, As a newbie, I'm desperate ro make my shell script work. I'd like a script which checks all the files in a directory, check the file name, if the file name ends with "extracted", store it in a variable, if it has a suffix of ".roi" stores in another variable. I'm going to use these two... (3 Replies)
Discussion started by: armando110
3 Replies

5. Shell Programming and Scripting

Search a test file for specific words

I have the need to search a text file from my unix script to determine if it contains the strings of: 'ERROR' and/or 'WARNING'. By using Grep I can search the file and return a where one of these strings exists. Like this: cat myfile.txt | grep ERROR Output: PROCESS ERROR HERE ... (3 Replies)
Discussion started by: buechler66
3 Replies

6. UNIX and Linux Applications

Reading a file for specific words

Hi I have a script where the user calls it with arguments like so: ./import.sh -s DNSNAME -d DBNAME I want to check that the database entered is valid by going through a passwd.ds file and checking if the database exists there. If it doesn't, the I need to send a message to my log... (4 Replies)
Discussion started by: ladyAnne
4 Replies

7. Shell Programming and Scripting

To fetch specific words from a file

Hi All, I have a file like this,(This is a sql output file) cat query_file 200000029 12345 10001 0.2 0 I want to fetch the values 200000029,10001,0.2 .I tried using the below code but i could get... (2 Replies)
Discussion started by: girish.raos
2 Replies

8. AIX

find for specific content in file in the directory and list only file names

Hi, I am trying to find the content of file using grep and find command and list only the file names but i am getting entire file list of files in the directory find . -exec grep "test" {} \; -ls Can anyone of you correct this (2 Replies)
Discussion started by: madhu_Jagarapu
2 Replies

9. UNIX for Dummies Questions & Answers

Search File for Specific Words

I have a file that contains the following: Mon Dec 3 15:52:57 PST 2o007: FAILED TO PROCESSED FILE 200712030790881200.TXT - exit code=107 Tue Dec 4 09:08:57 PST 2007: FAILED TO PROCESSED FILE 200712030790879200a.TXT - exit code=107 This file also has a lot more stuff since it is a log file.... (2 Replies)
Discussion started by: mevasquez
2 Replies

10. Shell Programming and Scripting

how to find capital letter names in a file without finding words at start of sentence

Hi, I want to be able to list all the names in a file which begin with a capital letter, but I don't want it to list words that begin a new sentence. Is there any way round this? Thanks for your help. (1 Reply)
Discussion started by: kev269
1 Replies
Login or Register to Ask a Question