简体   繁体   中英

How to get list of file names and their sentence containing a specific search string?

I tried with following command on unix machine:

ls -l | awk '{print $9}' | xargs -I {} cat  {}  | grep {"String to search"}

Though this works with text files but when i try it with xml files it is not able to display proper grepped text.Instead it displays whole xml file.

I think the possible reason behind this is absense of new line character in xml file that i use.

Example: Search string: "/1031/"

Xml line containing search string: <eventtype uri="{any_url}/1031/"/>

To clarify a bit :

ls -l | awk '{print $9}' | xargs -I {} cat {} | grep -o "/1031"

This gives output as:

/1031

/1031

/1031...

I also want the name of the file in which it belongs.

grep has a flag -o which only outputs the matching text.

ls -l | awk '{print $9}' | xargs -I {} cat {} | grep -o {"String to search"}

From your edit it looks like you need the "line" that contains the URL as well. By default grep will match greedily which means a regex to account for the XML formatting will still give you an incorrect result.

I can think of 2 possible options:

For the next examples, test.xml contains the string:

<eventtype uri="{www.example1.com}/1031/"/><eventtype uri="{www.example2.com}/1031/"/><eventtype uri="{www.example3.com}/1031/"/>

The first is to use the -P flag for grep to enable perl syntax and match lazily.

grep -Po '".*?/1031/"' test.xml 

This outputs:

"{www.example1.com}/1031/"
"{www.example2.com}/1031/"
"{www.example3.com}/1031/"

The second is to use sed to manually append a newline after each match and pipe to grep:

sed 's/1031/1031\n/g' test.xml | grep 1031

Outputs:

<eventtype uri="{www.example1.com}/1031
/"/><eventtype uri="{www.example2.com}/1031
/"/><eventtype uri="{www.example3.com}/1031

I believe both methods should work ok on plain text files although you may need to conditionally use one of these methods on .xml extensions.

Dear You could use below command

find -type f -exec grep -HPo '".*?/1031/"' {} \;

Sample Output

[root@MUM03S001 ~]# find -type f -exec grep -HPo '".*?/1031/"' {} \\;

./File:"{www.example1.com}/1031/"

./File:"{www.example2.com}/1031/"

./File:"{www.example3.com}/1031/"

[root@MUM03S001 ~]#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM