Add words to a text file using a single terminal command (no editors)
I'm new to Linux. I need to edit a .conf
file from the open terminal only and not using any text editors. That is, can I add words and sentences to a config file from an open terminal?
Example: command /home/.../file.conf -add 'abcd'
to the 23rd line and so on. And finally, save it.
Is it possible to search a specific word in that config file and add new text to the next line of that config file using only the command?
I usually do this way when I am programming my script to do same what you are asking but programmatically.
echo "Hello you!" >> myfile.txt
echo "this is 2nd line text" >> file.txt
echo "last line!" >> file.txt
Voila! You got it. Important to note >>
means adding new line to existing file meanwhile >
just simply overwrite everything.
Adding words and sentences to a config file from open terminal can be easily achieved with sed.
sed -i '23iabcd' file.conf
inserts at line 23 the text abcd
into file file.conf
-i
does the modification directly to file file.conf
.
If you want to use awk
then:
awk -v n=23 -v s="abcd" 'NR == n {print s} {print}' file > file.conf
The following adds one line after SearchPattern.
sed -i '/SearchPattern/aNew Text' SomeFile.txt
It inserts New Text one line below each line that contains SearchPattern.
To add two lines, you can use a \
and enter a newline while typing New Text.
sed -i '/pattern/a \
line1 \
line2' inputfile
You can also use the printf
command.
To add lines to your file
$ printf "\nThis is a new line to your document" >> file.txt
To overwrite the file
$ printf "This overwrites your file" > file.txt