0

How append data to same line of text file ? Case is first part is output of command and another is my special text, for e.g with code $ date >> file.txt && echo -n "new data" >> file.txt, here first output of date is stored first in file and text "new data" on new line, If I change the sequence of code for e.g -$ echo "new data ">> file.txt && date >> file.txt then it apeend the data on same line but I wanna append the date output first then the special text. How can I?

0

The date command automatically adds the newline at the end of the command. To remove this newline you could do:

date | tr -d '\n' >> file.txt && echo -n "new data" >> file.txt

This will remove any newlines from the date output.

  • thnx, It also works – AlphaCoder Feb 4 at 6:50
2

try

echo $(date) "new data" >> file.txt

where

  • $( ) substituion will strip new line of date.
  • 1
    As long as "new data" doesn't contain anything which has meaning as a date formatting code, date +"%c new data" >>file.txt might be more idiomatic. – tripleee Feb 4 at 12:39
1

Solution with removing newline character using substitution.

$ d=$(date)
$ echo -n $d >> file
$ echo " <- this is date" >> file
$ cat file
Mon Feb 4 07:08:21 CET 2019 <- this is date
$
  • @KamilMaciorowski Yeah, I found it too. I thought that ${d:-2} will strip last character but now, I don't know. :/ – Matej Feb 4 at 6:25
  • thnx,It Works also – AlphaCoder Feb 4 at 6:49
1

Another option, for the case where "new data" is static:

printf '%s new data\n' "$(date)" >> file.txt

For the situation where "new data" could vary:

printf '%s %s\n' "$(date)" "${newdatavar}" >> file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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