Insert Text – How to Insert Text in Specific Lines of a File

awkbashsedtext processing

How can I insert some text in specific lines of a file? What is the simplest method that I can use? (bash, sed, awk?)

What I want to do might be simple, but I don't know where I should start. It takes too much time for me to try to do this manually (I have a lot of files that I have to change for Excel/Calc later use).

Here is my input file example:

4.06
4.05
5.04
4.06
34.50
56.06
45.33
36.44

And I want something like this (insert text before line 1 and 5):

Exp1    
4.06
4.05
5.04
4.06
Exp2
34.50
56.06
45.33
36.44

How can I do this?

Best Answer

awk 'NR==1{print "Exp1"}NR==5{print "Exp2"}1' file

1 at the end means {print}.

sed '1i\
Exp1
5i\
Exp2
' file

If you want to extend it to more numbers, awk makes that easy:

awk 'NR%4==1{print "Exp"++i}1' file

With different numbers, we'll just say sed isn't the right tool for the job. It's possible, but not pretty.


As an academic curiosity, here it is in sed:

sed '1{ 
    h
    s/^.*$/Exp0/
    x   
}
x
s/^4//
s/^3/4/
s/^2/3/
s/^1/2/
/^E/ { 
    s/$/|/
    :x
    s/0|/1/
    s/1|/2/
    s/2|/3/
    s/3|/4/
    s/4|/5/
    s/5|/6/
    s/6|/7/
    s/7|/8/
    s/8|/9/
    s/9|/|0/
    tx
    s/^Exp|/Exp1/
    p
    s/^/1/
}
x' file
Related Question