yugendran
yugendran

Reputation: 19

Insert a line in a file based on pattern

I want to insert the new line in a file using sed command

sed -i  "/pattern to match/i\ new string to insert" etc/dir.txt

This command insert a new line like this, I want to insert the line with the leading spaces in the previous line.

the pattern should be: eod_clusterName: DEV_WAS_eBBSEOD_CN_DC The line should nsert before or after the pattern line, not the EOF.

earFileName: DEV_WAS_eBBS_CN_APP.ear
    eod_appName: DEV_WAS_eBBSEOD_CN_APP
    eod_clusterName: DEV_WAS_eBBSEOD_CN_DC
new string to insert

I want to insert new line like, It should automatically follow the leading spaces in the pattern and insert the new line in the file like below

earFileName: DEV_WAS_eBBS_CN_APP.ear
    eod_appName: DEV_WAS_eBBSEOD_CN_APP
    eod_clusterName: DEV_WAS_eBBSEOD_CN_DC
    #new string to insert#

Upvotes: 1

Views: 68

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed '/eod_clusterName: DEV_WAS_eBBSEOD_CN_DC/{p;s/\S.*/new string to insert/}' file

Focus on the line in question, print it and then replace it from the first non-whitespace character to the end of the line with the replacement text.

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

As far as I know i command can't do that. But you can insert a new line using s as well, capturing leading blanks in the current line, and preceding the new line with them. E.g:

sed 's/^\([[:space:]]*\).*pattern to match.*/&\n\1new string to insert/' file

Examples:

$ sed 's/^\([[:space:]]*\).*clusterName.*/&\n\1new string to insert/' file
earFileName: DEV_WAS_eBBS_CN_APP.ear
    eod_appName: DEV_WAS_eBBSEOD_CN_APP
    eod_clusterName: DEV_WAS_eBBSEOD_CN_DC
    new string to insert
$
$ sed 's/^\([[:space:]]*\).*DEV.*/&\n\1new string to insert/' file
earFileName: DEV_WAS_eBBS_CN_APP.ear
new string to insert
    eod_appName: DEV_WAS_eBBSEOD_CN_APP
    new string to insert
    eod_clusterName: DEV_WAS_eBBSEOD_CN_DC
    new string to insert

Upvotes: 1

Related Questions