0

I'm trying to create a script which inserts a line at the end of a file. But if I call the script multiple times It shouldn't create the same entry multiple times in the file.

So If I'm inserting the file on the 21st line, which I know is the end of that file.

sed -i '21s/.*/IP=192.168.1.1/' ip

21st line is empty and because of that this command is not working. Is there anyway to insert a line to an empty string, by modifying this command?

I know of other methods to append to the end of file, but my major concern is not to create copies of the same line if the script is called multiple times.

Gopikrishnan R
  • 11
  • 1
  • 1
  • 4

3 Answers3

1

With sed:

sed -i '${/IP=192\.168\.1\.1/!s/.*/&\nIP=192.168.1.1/}' file

How it works:

  • $: matches last line of the file
  • /IP=192\.168\.1\.1/!: if the last line doesn't contain the ip
  • s/.*/&\nIP=192.168.1.1/: replace it with its content followed by a newline followed by IP=192.168.1.1
SLePort
  • 15,211
  • 3
  • 34
  • 44
-1

Try with this if sentence:

 if [[ $(tail -1 filename.txt) != IP=192.168.1.1 ]]; then echo "IP=192.168.1.1" >> filename.txt; fi

It may append "IP=192.168.1.1" at the end of the file in case of this is not the last line.

Zumo de Vidrio
  • 2,021
  • 2
  • 15
  • 33
-1

You can do it by using awk:

awk -v "total=$(wc -l file.1 | awk '{print $1}')" '{if(total==NR && $0 != "IP=192.168.1.1") { print "IP=192.168.1.1" } else  { print $1 } }' file.1

And if you want to save output, just redirect output to a file.

Ali Okan Yüksel
  • 338
  • 1
  • 13
  • This solution will overwrite the last line, I think OP doesn't want to overwrite, just append after last non empty line of a file. – Zumo de Vidrio Mar 23 '17 at 09:05
  • Zumo you are wrong. It doesn't append the same line, if the line already exists. Please check if statement. – Ali Okan Yüksel Mar 24 '17 at 09:10
  • For some reason if I try your command with a sample file if last line does not match with the IP line, then it overwrites the last line of my file with the IP line and if last line matches with IP line, then that same line is duplicated. – Zumo de Vidrio Mar 24 '17 at 10:23