Add lines to file linux

How to append output to the end of a text file

If file_to_append_to does not exist, it will be created.

$ echo "hello" > file $ echo "world" >> file $ cat file hello world 

The problem is that echo removes the newlines from the string. How do you append to a file a string which contains newlines?

echo does not remove newlines from the string. If you fail to properly quote the argument, then the shell will split the string and pass arguments to echo and echo never even sees the newlines.

@Pmpr note that echo is not part of the solution, it is only part of the example I typed, and there are no escape sequences in the example.

echo "hello world" >> read.txt cat read.txt echo "hello siva" >> read.txt cat read.txt 

then the output should be

hello world # from 1st echo command hello world # from 2nd echo command hello siva 
echo "hello tom" > read.txt cat read.txt 

You can use the >> operator. This will append data from a command to the end of a text file.

echo "Hi this is a test" >> textfile.txt 

Do this a couple of times and then run:

You’ll see your text has been appended several times to the textfile.txt file.

Use command >> file_to_append_to to append to a file.

For example echo «Hello» >> testFile.txt

CAUTION: if you only use a single > you will overwrite the contents of the file. To ensure that doesn’t ever happen, you can add set -o noclobber to your .bashrc .

This ensures that if you accidentally type command > file_to_append_to to an existing file, it will alert you that the file exists already. Sample error message: file exists: testFile.txt

Thus, when you use > it will only allow you to create a new file, not overwrite an existing file.

Using tee with option -a (—append) allows you to append to multiple files at once and also to use sudo (very useful when appending to protected files). Besides that, it is interesting if you need to use other shells besides bash, as not all shells support the > and >> operators

echo "hello world" | sudo tee -a output.txt 

This thread has good answers about tee

Use the >> operator to append text to a file.

I often confuse the two. Better to remember through their output:

> for Overwrite

$ touch someFile.txt $ echo ">" > someFile.txt $ cat someFile.txt > $ echo ">" > someFile.txt $ cat someFile.txt > 

>> for Append

$ echo ">" > someFile.txt $ cat someFile.txt > $ echo ">" >> someFile.txt $ cat someFile.txt >> 

this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.

Run the above with the cron every hour, or

while : do cmd >> o.txt && [[ $(wc -l  

I would use printf instead of echo because it's more reliable and processes formatting such as new line \n properly.

This example produces an output similar to echo in previous examples:

printf "hello world" >> read.txt cat read.txt hello world 

However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent

printf "hello\nworld" >> read.txt cat read.txt hello world 

I'd suggest you do two things:

  1. Use >> in your shell script to append contents to particular file. The filename can be fixed or using some pattern.
  2. Setup a hourly cronjob to trigger the shell script
Читайте также:  Установка принтера линукс терминал

For example your file contains :

 1. mangesh@001:~$ cat output.txt 1 2 EOF 

if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'

 2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 1 2 EOF somthing to append 

And to overwrite contents of file :

 3. mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx somthing new to write 

This is misleading in many details. Spaces are not important and piping an empty output to cat is . just completely wacky. (It's empty because you just redirected standard output to a file.)

In Linux, You can use cat command to append file content to another file

In the previous command you will append content of fileName_1.txt to fileName_2.txt .

In Windows OS you can use type command

type fileName_1.txt >> fileName_2.txt

While all of these answers are technically correct that appending to a file with >> is generally the way to go, note that if you use this in a loop when for example parsing/processing a file and append each line to the resulting file, this might be much slower then you would expect.

A faster alternative might be this:

stringBuilder="" while read -r line; do # $'\n' prints a newline so we don't have to know what special chars the string contains stringBuilder+="$line"$'\n' done < "myFile.txt" echo "$stringBuilder" >$file 

WARNING: you are reading all lines into memory; memory is a limited resource, so don't go doing this for gigantic files.

Источник

Command to append line to a text file without opening an editor

You can append a line of text to a file by using the >> operator:

echo "hello world" >> my_file.txt 
echo "alias list='ls -cl --group-directories-first'" >> config.fish 

I use echo myself, but be careful, if you only specify one > then the file will truncate, not append. for a safer command you can use sed: sed -i '$a hello world' filename

explanation: -i will update the file (otherwise it will just print the result to stdout), $ is regex that will match the end of the file, and a appends the following text to filename.

echo "hello world" >> my_file.txt does not create a new last line with HW , but add it to the string of the last line.

Maybe "Hello World" @7wp 🙂 It's echo that adds the line break (making it a line as opposed to just a bunch of characters). You can switch off the line break at the end with -n .

Adding to Stefano's answer, you can also use cat :

$ cat >> config.fish alias list='ls -cl --group-directories-first' > EOF 

I often use this method but recently got caught when I pasted in a text that included some (escape) codes. It didn't complain but when I checked the file there were chunks of pasted text missing. So use it with care!

Читайте также:  Networking with linux pdf

@elmclose Sorry, which method? They work differently with respect to metacharacters. I think the second one doesn't do anything with them, though there might be a few exceptions.

I meant EOF method. Very convenient and useful when you type or paste in readable text. But codes in my text confused the process. The file was a bash script that kept failing. Took me a while before I discovered what had happened.

There's plenty of methods of appending to file without opening text editors, particularly via multiple available text processing utilities in Ubuntu. In general, anything that allows us to perform open() syscall with O_APPEND flag added, can be used to append to a file.

    GNU version of dd utility can append data to file with conv=notrunc oflag=append

printf "\nalias list='ls -cl --group-directories-first'\n" | dd conv=notrunc oflag=append bs=1 of=config.fish 
sed -i '$a alias list='"'"'ls -cl --group-directories-first'"'" config.fish 
 #!/usr/bin/env python3 # read bytes from stdin, append to specified file import sys with open(sys.argv[1],'ab') as f: f.write(sys.stdin.buffer.read()) 

See also:

Источник

How to insert a text at the beginning of a file?

It's similar but I don't want to create any new line with it. I would like to do this with sed if possible.

20 Answers 20

sed can operate on an address:

What is this magical 1s you see on every answer here? Line addressing!.

Want to add on the first 10 lines?

$ < echo -n ''; cat file; > >file.new $ mv file

-i stands for in-place, you can append a suffix to -i to make a copy rather than overwrite. -i.new would make a new file ending with .new, but just -i would edit the file directly.

Note that the sed won't work on an empty file - afaict sed can't be made to do anything at all with 0-length input.

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

The best solution will add the string, but with the string, it will not add a line at the end of a file.

On Mac OS, was getting error with "undefined label". Found that you need to give an extension for a backup file; see mkyong.com/mac/…

Under Mac OS's sed version you have to supply backup file name with -i option. One can pass just an empty string for no backup like sed -i '' '1s/^/new test\n/' filename

If the file is only one line, you can use:

sed 's/^/insert this /' oldfile > newfile 

If it's more than one line. one of:

sed '1s/^/insert this /' oldfile > newfile sed '1,1s/^/insert this /' oldfile > newfile 

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

sed -i 'whatever command you choose' filename 
echo "$(echo -n 'hello'; cat filename)" > filename 

Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:

echo -n "hello" | cat - filename > /tmp/filename.tmp mv /tmp/filename.tmp filename 

Neither grouping nor command substitution is needed.

Читайте также:  Super slim ps3 установить linux

This is the superior and simpler solution to all the other ones using sed , which don't work for empty files.

printf '%s' "some text at the beginning" | cat - filename 

This would only output the text followed by the file's content, but it does not modify the file at all.

That's a good solution, I wonder why it didn't get any upvotes. Here's mine my good sir. Also, why printf and not a simple echo ?

I tried directing this into a file by appending > file to the command, it jus spammed my terminal with "some text at the beginning"

sed -i '1i /path/of/file.sh' filename 

This will work even is the string containing forward slash "/"

To add a line to the top of the file:

Note that on OS X, sed -i file , fails. However, if you provide a backup extension, sed -i old file , then file is modified in place while file.old is created. You can then delete file.old in your script.

I've found macOS sed wants a dot to edit in place without creating a backup: sed -i. file

echo "your header" > headerFile.txt cat yourFile >> headerFile.txt 

PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.

/mnt/Vancouver/Programming/file1 

tag the top of file1 with Programming .

SOLUTION 1 -- non-empty files:

bn=$ ## bn: basename sed -i '1s/^/'"$bn"'\n/'

1s places the text at line 1 of the file.

SOLUTION 2 -- empty or non-empty files:

printf "$\n" | cat - > temp && mv -f temp

Note that the - in the cat command is required (reads standard input: see man cat for more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp . See also the explanation at the bottom of http://www.linfo.org/cat.html.

I also added -f to the mv command, to avoid being asked for confirmations when overwriting files.

To recurse over a directory:

for file in *; do printf "$\n" | cat - $file > temp && mv -f temp $file; done 

Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f . -type solutions) for those.

ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:

#!/bin/bash ## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi ## To allow spaces in filenames, ## at the top of the script include: IFS=$'\n'; set -f ## at the end of the script include: unset IFS; set +f IFS=$'\n'; set -f # ---------------------------------------------------------------------------- # SET PATHS: IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/" # https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command # FILES=$(find $IN -type f -regex ".*/7*") ## recursive; numeric filenames only FILES=$(find $IN -type f -regex ".*/[0-9 ]*") ## recursive; numeric filenames only (may include spaces) # echo '$FILES:' ## single-quoted, (literally) prints: $FILES: # echo "$FILES" ## double-quoted, prints path/, filename (one per line) # ---------------------------------------------------------------------------- # MAIN LOOP: for f in $FILES do # Tag top of file with basename of current dir: printf "[top] Tag: $\n\n" | cat - $f > temp && mv -f temp $f # Tag bottom of file with basename of current dir: printf "\n[bottom] Tag: $\n" >> $f done unset IFS; set +f 

Источник

Оцените статью
Adblock
detector