Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

script to find a missing pattern and add text 1

Status
Not open for further replies.

tumichaelf

IS-IT--Management
May 17, 2011
33
0
0
US
I am writing script to read through a bunch of data, the script is below

Code:
#!/bin/bash

rm -f output.out

files=`find -name hgrc`
for file in $files ; do
srch=`grep -iq "[hooks]" $file`
if [ "$srch" == "0" ] ; then
echo $file >> output.out
fi
done

essentially, it is looking through the hgrc files and if it does not find the [hooks] text, it is echoing the path and filename to output.out.

What I need is a script to that search and add [hooks] as the last line of the file (there would be an empty line above it).

Any help is appreciated.
 
got it

Code:
#!/bin/bash

rm -f output.out

files=`find -name hgrc`
for file in $files ; do
  srch=`grep -ic "\[hooks\]" $file`
  if [ "$srch" == "0" ] ; then
     echo $file >> output.out
     #echo >> $file
     #echo "[hooks]" >> $file
  fi
done
 
Hi

Just some minor notes :
[ul]
[li]If the path to file hgrc contains whitespace characters, your [tt]for[/tt] will fail because of erroneous word splitting. Pipe into [tt]while[/tt] [tt]read[/tt] instead.[/li]
[li]You seems to be interested in whether the file contains the given string, not how many times it contains. So better use [tt]-q[/tt] ( [tt]--quiet[/tt] ) instead of [tt]-c[/tt] ( [tt]--count[/tt] ), as it is faster.[/li]
[li]There you are searching for a fixed string, so better tell that to [tt]grep[/tt] with then [tt]-F[/tt] ( [tt]--fixed-strings[/tt] ) option as it is faster than regular expression.[/li]
[/ul]
Code:
find -name hgrc [teal]|[/teal]
[b]while[/b] [b]read[/b] file[teal];[/teal] [b]do[/b]
  grep -iqF [green][i]'[hooks]'[/i][/green] [green][i]"$file"[/i][/green] [teal]||[/teal] {
    echo [green][i]"$file"[/i][/green] [teal]>>[/teal] output[teal].[/teal]out
    [gray]#echo >> "$file"[/gray]
    [gray]#echo '[hooks]' >> "$file"[/gray]
  }
[b]done[/b]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top