-1

I'm using grep to find a string in a file. The grep will probably only find one file that matches the file name, possibly two, but i only need it to put the string if it found it, and just the string.

grep -oh 'Closing finished' /opt/cpu/hold/closing15{14..23} 

Currently i get an output like:

grep: /opt/cpu/hold/closing1514: No such file or directory
Closing finished
Closing finished
grep: /opt/cpu/hold/closing1517: No such file or directory
grep: /opt/cpu/hold/closing1518: No such file or directory

I'm using this in a function in a bash script, in an until loop to match "Closing finished" before moving on. So i want the output to just be "Closing finished" if found so it matches my until condition.

T_Wrong
  • 59
  • 5

1 Answers1

2

If what you want is to supress the errors about non-existent files, simply use the -s option:

-s, --no-messages
       Suppress error messages about nonexistent or unreadable files.

I.e. your example command should look like:

grep -soh 'Closing finished' /opt/cpu/hold/closing15{14..23} 

Alternatively you can also supress the error output altogether by redirecting it to /dev/null like so:

grep -oh 'Closing finished' /opt/cpu/hold/closing15{14..23} 2>/dev/null
Jiri Valenta
  • 500
  • 2
  • 8
  • This is it, thank you so much! IF it does find 2 strings in 2 files, is there a way to suppress that output, so it only outputs the string once? – T_Wrong Jan 15 '20 at 20:34
  • answered my own questions. I'll just add a line of awk for row 1. – T_Wrong Jan 15 '20 at 20:40
  • `grep` has an option `-m N` to stop searching after Nth match, but it applies in the context of reading a single file. For example `-m 1` would make it stop after finding the first match in given file. But when you're matching across multiple files, it would still continue searching in the remaining files (and again print only the first match from each file). You can simply append `| head -n 1` after your grep to print just the first match from all files BTW this already has an answer [here](https://stackoverflow.com/questions/14093452/grep-only-the-first-match-and-stop) ;) – Jiri Valenta Jan 15 '20 at 20:42
  • @T_wrong you don't need grep if you're using awk so if grep alone isn't adequate to solve your problem then use awk alone, not both of them. In this case you could pipe the grep output to `sort u` to only get 1 "Closing finished" max. Ask a new question if you'd like more help. – Ed Morton Jan 15 '20 at 21:21