Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a text file divided in stanzas. Each stanza starts with a [keyword] and ends with a blank line. Something like this:

[keyword1]
param1 = value1
param2 = value2
param3 = value3

[keyword2]
param4 = value4
param5 = value5
...

I need a script (probably a one line command will work) to insert 2 lines immediately after a given [keyword]. Lines to be inserted are like the above couples:

param = value

I was thinking about using sed with in place editing plus a backup copy file just in case.

share|improve this question
add comment

2 Answers 2

Yes, sed sounds like the right choice:

sed -i.bak '/^\[keyword1\]/aparam = value\nparam = other' your.file

awk can do it, excepting the in-place editing part:

awk '1;/^\[keyword1\]/{print"param = value";print"param = other"}' your.file > new.file

If you not care about using a big gun like perl for such a small task:

perl -i.bak -pe '$_.="param = value\nparam = other\n"if/^\[keyword1\]/' your.file

The later one will work in ruby with 1 character modification:

ruby -i.bak -pe '$_+="param = value\nparam = other\n"if/^\[keyword1\]/' your.file

python solution is somehow lengthy (probably worsened by my knowledge's weakness):

python -c 'import sys,fileinput;[sys.stdout.write(line+("param = value\nparam = other\n" if line=="[keyword1]\n" else "")) for line in fileinput.input(inplace=1,backup=".bak")]' your.file

Again without the in-place editing, but bash and ksh can do it too:

while IFS='' read -r line; do
  echo "$line"
  [[ "$line" == '[keyword1]' ]] && {
    echo "param = value"
    echo "param = other"
  }
done < your.file > new.file

With ed is simple to edit in-place, but I know no way to create backup:

ed -s your.file <<< $'/^\[keyword1\]/a\nparam = value\nparam = other\n.\nwq'
share|improve this answer
    
you are my personal wiki-hero! :) thanks! –  ztank1013 Nov 9 '11 at 13:37
add comment

If you use vim as your editor, you can set up abbreviations in your .vimrc as follows:

:abbr key1 [keyword1]^M^Iparam1 = value1^M^Iparam2 = value2^M^Iparam3 = value3^M
:abbr key2 [keyword2]^M^Iparam4 = value4^M^Iparam5 = value5^M

Now, in any file, in insert mode, if you type key1, and press enter, you'll see:

[keyword1]
       param1 = value1
       param2 = value2
       param3 = value3

If it's the sort of thing you do often, and repetitively, vim abbreviations can ease the pain.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.