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 -.

Share:
8,765

Related videos on Youtube

xenoterracide
Author by

xenoterracide

Former Linux System Administrator, now full time Java Software Engineer.

Updated on September 17, 2022

Comments

  • xenoterracide
    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
    
  • Hari
    Hari over 13 years
    The '!' 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'
    Gilles 'SO- stop being evil' over 13 years
    @Hari: ! wasn't in Bourne, but it is in POSIX.