how to find a file name that contains a string “abcd ” in the file content from multiple files in the directory using awk

孤人 提交于 2020-06-17 09:55:47

问题


the "bookrecords" directory has multiple files

bookrecords
           1.txt
           2.txt 
           3.txt .....

file 2.txt has the content

2.txt
    author: abcd
    title:  efg
    year: 1980

how can I get the file name 2.txt by using author: as a keyword

using awk command

I try to use grep command but I want to use awk command

SearchRecord()
{


  name = abcd
  total=`cat $bookrecords | grep -cwi $name`
  record=`cat $bookrecords | grep -wi $name`

  menu
}

回答1:


with awk

$ awk -v search_string="$name" '$0~search_string{print FILENAME; exit}' bookrecords/*

however, I think grep is better if you're not structurally searching

$ grep -lF "$name" bookrecords/*



回答2:


If you have a deep directory hierarchy below bookrecords, you could do a

grep -Elsrx '[[:space:]]*author:[[:space:]]*abcd[[:space:]]*' bookrecords

If you only want to look at *.txt files inside bookrecords, do a

grep -Elx '[[:space:]]*author:[[:space:]]*abcd[[:space:]]*' bookrecords/*.txt

The -l produces only the file names in the output, and -x takes care that the regular expression matches the whole line. Hence, a line containing myauthor:abcde would not be selected. Adapt the regexp to your taste, and be careful when replacing abcd by a real author name (it should not contain unescaped regexp characters, such as for instance a period).

If you want to start the line with at least one white space, and have at least one space after the colon:

grep -Elsrx '[[:space:]]+author:[[:space:]]+abcd[[:space:]]*' bookrecords


来源:https://stackoverflow.com/questions/62312824/how-to-find-a-file-name-that-contains-a-string-abcd-in-the-file-content-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!