Sed: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 4: Line 4:


=Insert a Line/Append in a Specific Position (line number) in a file=
=Insert a Line/Append in a Specific Position (line number) in a file=
Figure out the line number:
<pre>
# determine the last line that contains ^JAVA_OPTS
local n
n=$(cat ${f} | grep -n "^JAVA_OPTS=" | tail -1) || { echo "failed to determine the line number" 1>&2; exit 1; }
n=${n%%:*}
</pre>
Insert a line at line 'n':
<pre>
# insert at line "n":
cat ${f} | sed -e ${n}'a\
This line will be inserted at line number '"${n}"', and this '"${variable}"' will be substituted' > ${dest}
</pre>
To append at a specific line number, determine the line number as before and effectively "substitute" (s) the line end with your addition:
<pre>
cat ${f} | sed -e ${n}'s/$/this text will be appended at line number, and this '"${variable}"' will be substituted\n' > ${dest}
</pre>


=Special Characters (need to be escaped in regular expressions)=
=Special Characters (need to be escaped in regular expressions)=

Revision as of 03:17, 16 February 2016

Internal

Insert a Line/Append in a Specific Position (line number) in a file

Figure out the line number:

# determine the last line that contains ^JAVA_OPTS
local n
n=$(cat ${f} | grep -n "^JAVA_OPTS=" | tail -1) || { echo "failed to determine the line number" 1>&2; exit 1; }
n=${n%%:*}

Insert a line at line 'n':

# insert at line "n":
cat ${f} | sed -e ${n}'a\
This line will be inserted at line number '"${n}"', and this '"${variable}"' will be substituted' > ${dest}

To append at a specific line number, determine the line number as before and effectively "substitute" (s) the line end with your addition:

cat ${f} | sed -e ${n}'s/$/this text will be appended at line number, and this '"${variable}"' will be substituted\n' > ${dest}

Special Characters (need to be escaped in regular expressions)