Assuming i have a line that i want to add to a file without opening an editor.
How could i append this line
alias list='ls -cl --group-directories-first'to this file
config.fish 3 Answers
You can append a line of text to a file by using the >> operator:
echo "hello world" >> my_file.txtor in your case
echo "alias list='ls -cl --group-directories-first'" >> config.fishPlease take note of the different types of quotes.
8Adding to Stefano's answer, you can also use cat:
Using a heredoc:
$ cat >> config.fish <<'EOF' > alias list='ls -cl --group-directories-first' > EOF<<'EOF'means "take the following as input, until you reach a line that is justEOF". The quotes mean to take the input literally.Or inputting the line on stdin:
$ cat >> config.fishThen paste or type in the line, press Enter to go to a new line, then press Ctrl+D to mark the end.
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
ddutility can append data to file withconv=notrunc oflag=appendprintf "\nalias list='ls -cl --group-directories-first'\n" | dd conv=notrunc oflag=append bs=1 of=config.fishPortably we could use something like this on the right side of pipeline:
dd conv=notrunc seek=$(wc -c < testFile.txt) bs=1 of=testFile.txtNote the use of
bs=1, which is to prevent short reads from pipelineThe
teecommand can be used when you need to append to file and send it to stdout or to next command in pipelinetee -a config.fish <<< "alias list='ls -cl --group-directories-first'"awkhas append operator>>which is also portable and defined by POSIX specificationsawk 'BEGIN{ printf "alias list=\x27ls -cl --group-directories-first\x27\n" >> "config.fish" }'We can combine
sed's flag$to match the last line withafor appending and-ifor in-place editing.sed -i '$a alias list='"'"'ls -cl --group-directories-first'"'" config.fishWe could even implement something like
ddin Python 3:
#!/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())