Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add line to a file ONLY if it is not in file already [duplicate]

Tags:

linux

grep

sed

I want to add the following line:

nohup java -jar /mnt/fusion/nfs/labStats/LabInfoAutoLog.jar > /dev/null &

to the end of the file /etc/rc.d/rc.local if it does not already exist.

How can I do that from linux command line? I assume grep or sed would work, but I am not familiar enough with either to get it to work. Right now I use echo, but that just keeps adding it over and over again.

like image 345
cHam Avatar asked Jul 19 '13 14:07

cHam


People also ask

How do I add a new line to a file?

|| echo >> "$f" appends a newline to the file if the exit status of the previous command was nonzero.

How can I append some lines in existing file using which command?

You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems.

How do I add a new line to an existing file in Linux?

Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.


2 Answers

Assuming you want it at the end of the file:

LINE="nohup java -jar /mnt/fusion/nfs/labStats/LabInfoAutoLog.jar > /dev/null &"
FILE=/etc/rc.d/rc.local
grep -q "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
like image 129
ahilsend Avatar answered Sep 23 '22 03:09

ahilsend


one option is two steps:

grep -q "yourline" /path/file||sed -i '/..place../ a \the line' file

also possible to do with awk,

save all lines in array, during saving if the line was found, exit. otherwise, add the line in END{} block to the right place.

P.S. You didn't tell in the file, where to add that line.

like image 38
Kent Avatar answered Sep 25 '22 03:09

Kent