How do I check if a file already has line with "contents" in it?
8,765
Solution 1
#!/bin/bash
LINE='eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)'
if ! grep -qF "$LINE" file.txt ; then echo "$LINE" >> file.txt ; fi
The $(...) will return the result of the command, not the errorlevel value. Use without command substitution to get the proper return code.
Solution 2
To search for a literal string:
line='eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)'
file=~/.bashrc
if ! grep -q -x -F -e "$line" <"$file"; then
printf '%s\n' "$line" >>"$file"
fi
-q
suppresses grep
output (you're only interested in the return status). -x
requires the whole line to match. -F
searches for a literal string rather than a regexp. -e
is a precaution in case $line
starts with a -
.
Related videos on Youtube
Author by
xenoterracide
Former Linux System Administrator, now full time Java Software Engineer.
Updated on September 17, 2022Comments
-
xenoterracide over 1 year
I need to know if a file aready has line with contents X in it, if not append line. here's the code I've tried.
if ! $(grep 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' ~/.bashrc) then echo 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' >> ~/.bashrc fi
-
Admin over 13 yearsI answered a similar question on stackoverflow: stackoverflow.com/questions/4479579/…
-
-
Hari over 13 yearsThe '!' command isn't always available in 'sh', IIRC (yeah, I know you used bash). It might be slightly more idiomatic sh to say: grep -qF "$LINE" file.txt || echo "$LINE" >> file.txt
-
Gilles 'SO- stop being evil' over 13 years@Hari:
!
wasn't in Bourne, but it is in POSIX.