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?
25 Answers
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.txtVoila! 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.confinserts 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.confThe following adds one line after SearchPattern.
sed -i '/SearchPattern/aNew Text' SomeFile.txtIt 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.txtTo overwrite the file
$ printf "This overwrites your file" > file.txt awk '{if ($1 ~ /regex/) print $1 "content to be added"; else print $1}' < inputfile > outputfileNotes:
- regex is a regular expression (also known as regex), it defines the search criteria. Regular expressions allow for very customizable searches and the syntax understood by awk is in the manual. In the simplest case - search a string "as it is", character by character - just put a backslash before special characters (see manual for the list of special characters)
How it works:
- open
inputfilefor reading the input lines, clearoutputfileand open it for writing the output lines - for each line, run the block in braces:
- if the line matches the regular expression, then output the line with content appended
- otherwise, output the very same line.
I found a solution to my own question using the ed command
ed -s /home/.../abc.conf <<< $'23i\ntext\n.\nwq'Text can contain 27 lines. You can copy 27 lines from a text file and paste 27 lines to your config file. But I need to run the ed command simultaneously in order to add more text to the same config file.