2

I am trying to remove the last newline added to the file using bash script. I have got this - truncate -s $(($(stat -c '%s' foo.txt)-1)) foo.txt

here foo.txt the file name. but I want to parametrize the file name, I will pas the file name to the script and it should this remove the newline at last from that file. Request your help on this. I do not have linux in my machine and tried using cygwin but it is giving error while running the script.

Thanks

5
  • here is example - <1#3#5#3 1#7#6 1#5#6#9#9> Commented Feb 1, 2015 at 4:02
  • each line is separated by new line, I tried to add but did not work, want to remove the last new line after 1#5#6#9#9 Commented Feb 1, 2015 at 4:04
  • I have a tab delimited file, each line of which is separated by newline. I want to remove only the newline which is after the last record in the file. for this I have the code - <truncate -s $(($(stat -c '%s' foo.txt)-1)) foo.txt> but here the file name is hardcoded as foo.txt. I want to pass the filename to the bash script as a parameter so that it will remove the last newline from that particular file. Commented Feb 1, 2015 at 4:18
  • Is newline is the only character on last line?
    – anubhava
    Commented Feb 1, 2015 at 4:19
  • yes newline is the only char on last line Commented Feb 1, 2015 at 4:21

1 Answer 1

1

To remove last line if it is newline use this sedL

sed -i.bak '/^[[:blank:]]*$/{$d;}' foo.txt 
6
  • hey thanks, but when I am opening using notepad++ the file remains same. can we remove the last byte using that code and include this in a script and call the script with a parameter file name. Commented Feb 1, 2015 at 4:37
  • Show output of tail -1 foo.txt | cat -vte
    – anubhava
    Commented Feb 1, 2015 at 4:39
  • that was the output in the console, not sure if I have done something wrong Commented Feb 1, 2015 at 4:49
  • I want to remove the newline after the last record and move up the cursor to the end of the last record. that other code is working , but I want it to parameterized with the filename. the other code mentioned by me is removing the last byte (which is for new line) from the file. Commented Feb 1, 2015 at 4:52
  • 1
    But you wrote above last line has only newline character.?
    – anubhava
    Commented Feb 1, 2015 at 4:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.