Bash: Inserting a line in a file at a specific location
If you want to add a line after a specific string match:
$ awk '/master.mplayer.com/ { print; print "new line"; next }1' foo.input
ServerActors=IpServer.UdpServerUplink MasterServerAddress=unreal.epicgames.com MasterServerPort=27900
ServerActors=IpServer.UdpServerUplink MasterServerAddress=master0.gamespy.com MasterServerPort=27900
ServerActors=IpServer.UdpServerUplink MasterServerAddress=master.mplayer.com MasterServerPort=27900
new line
ServerActors=UWeb.WebServer
Insert lines in a file starting from a specific line
This can be done with sed: sed 's/fields/fields\nNew Inserted Line/'
$ cat file.txt
line 1
line 2
fields
line 3
another line
fields
dkhs
$ sed 's/fields/fields\nNew Inserted Line/' file.txt
line 1
line 2
fields
New Inserted Line
line 3
another line
fields
New Inserted Line
dkhs
Use -i
to save in-place instead of printing to stdout
sed -i 's/fields/fields\nNew Inserted Line/'
As a bash script:
#!/bin/bash
match='fields'
insert='New Inserted Line'
file='file.txt'
sed -i "s/$match/$match\n$insert/" $file
Add a line in a specific position with Linux and output to the same file?
The only way to do this is to write to a second file, then replace the original. You can only append to an arbitrary file; you cannot insert into the middle of one.
t=$(mktemp)
sed '3iline 3' file.txt > "$t" && mv "$t" file.txt
If your version of sed
supports it, you can use the -i
option to automate the handling of the temporary file.
sed -i '3iline 3' file.txt # GNU
sed -i "" '3iline 3 ' file.txt # BSD sed requires an argument for -i
How to insert variable into file at a specified position
Perhaps try and integrate this solution using sed:
sed -i -E "s/(^hotfix\.dlFilePath\=\/opt\/files\/)(.*$)?/\1$files/" config.properties
Please note the use of double quotes around the substitution expression in sed to make the shell expand variables. So, with a variable like this
files="foo"
and given this input (assuming that the <file> was just a placeholder):
rest.server.url=https\://hostname/RestService/
rest.username=user
rest.password=pass
rest.response.type=json
hotfix.async=false
hotfix.operation=hotfix
hotfix.dlFilePath=/opt/files/
you'll get this result
rest.server.url=https\://hostname/RestService/
rest.username=user
rest.password=pass
rest.response.type=json
hotfix.async=false
hotfix.operation=hotfix
hotfix.dlFilePath=/opt/files/foo
inserting contents of one text file into another in bash
If you want to edit a file directly, I always suggest ed
instead of the non-standard sed -i
(Where different implementions of sed
that do support it act differently, a common source of questions here):
printf "%s\n" "/TWO/r ext" w | ed -s base
will insert the contents of file ext after the first line containing TWO in base, and then write the new version of base back to disk.
If you must use sed
, the proper invocation will look very similar (No surprise since they're sibling commands):
sed -i '/TWO/r ext' base
(This will insert the ext file after every TWO in base, though, not just the first.)
The key in both is the r
command, which reads the contents of the given file and inserts it after a line with the matching address. Works a lot better than trying to read the file contents into a variable and including the text directly in the ed
/sed
commands.
If you want to insert the contents of a variable after the line, you can use
printf "%s\n" "/TWO/a" "$ext" . w | ed -s base
(As long as the variable doesn't have a line with just a period)
or with GNU sed
sed -i "/TWO/a ${ext//$'\n'/\\\n}" base
to append text after the addressed line.
Insert content of file at specific line number of another file in LINUX/BASH
You can do it with awk
fairly easily using a variable to serve as a flag to only write the contents of tempfile
once after the first occurrence of "@type ABCDF"
. The approach is simple, you output every line with the first {print}
rule, then if /@type ABCDF/ && n
, you loop with getline
reading each line from tempfile
and outputting it. When done outputting the file, you simply set n=0
and it will skip all the other occurrences of "@type ABCDF"
in the file, e.g.
awk -vn=1 '{print}; /@type ABCDF/ && n{while (getline <"tempfile") print;n=0}' file1
Example Input file1
$ cat file1
File1
@type ABCDF #---Insert 'tempfile' content below First occurrence '@type ABCDF'
File2
File3
@type ABCDF
File4
@type ABCDF
File5
Example Use/Output
$ awk -vn=1 '{print}; /@type ABCDF/ && n{while (getline <"tempfile") print;n=0}' file1
File1
@type ABCDF #---Insert 'tempfile' content below First occurrence '@type ABCDF'
tempFile 01
tempFile 02
tempFile 03
tempFile 03
File2
File3
@type ABCDF
File4
@type ABCDF
File5
You can redirect the output to a temporary file and then replace the original to emulate an in-place addition of the lines.
Bash: How can I insert a line to a specific location within a file?
This awk should work:
awk -v a="mysite" '/<VirtualHost /{v=1}
v && /^ *ServerAlias/{{$0=" ServerAlias " a ".booking.local" RS $0; v=0}
/<\/VirtualHost>/{v=0} 1' file
OURPUT:
<VirtualHost *:80>
ServerName www.sitename.com
ServerAlias sitename.booking.local
ServerAlias sitename.com
DocumentRoot /site/http/travel/itn
CustomLog logs/access_sitename_log combined
DirectoryIndex default.php index.php index.html index.phtml index.cgi index.htm
ScriptAlias /awstats/ /usr/local/awstats/wwwroot/cgi-bin/
<Directory /site/http/travel/itn >
AllowOverride All
</Directory>
</VirtualHost>
Related Topics
How to Search for Files Containing Dos Line Endings (Crlf) with Grep on Linux
How to Create a Device Node from the Init_Module Code of a Linux Kernel Module
How to Trim White Space from a Variable in Awk
How to Remove the Bom from a Utf-8 File
Command Line Utility to Print Statistics of Numbers in Linux
Getting CPU Cycles Using Rdtsc - Why Does the Value of Rdtsc Always Increase
How to Get Child Process from Parent Process
Identify User in a Bash Script Called by Sudo
Faster Forking of Large Processes on Linux
How to Get the Start Time of a Long-Running Linux Process
How to Automatically Add User Account and Password with a Bash Script
Ioctl VS Netlink VS Memmap to Communicate Between Kernel Space and User Space
Nginx: Serve Multiple Laravel Apps with Same Url But Two Different Sub Locations in Linux