Reputation: 139
So, I have a file called "burpfile". I want to add a specific line "peter" after every second line. An example burpfil can contain:
line1
line2
line3
line4
line5
I want the bashscript to modify it to become:
line1
peter
line2
peter
line3
peter
line4
peter
line5
peter
To realise this I have tried sed, since that was the choice in this post: https://stackoverflow.com/a/45964337/11155582
This is what I have got so far. However, since I don't understand sed the script only inserts "peter" at the end of the file. And I don't know why.
nr=$(wc -l burpfil | awk '{print $1}')
for i in $(seq 0 2 $nr)
do
sed -e '$i peter' -i burpfil
done
As seen in the codesnippet the command doesn't resemble what is in the thread I linked to. That is because having a variable in the command doesnt work... And I don't know how to get around it.
Upvotes: 1
Views: 3115
Reputation: 58351
This might work for you (GNU sed):
sed 'p;c peter' file
or if you prefer:
sed 'p;s/.*/peter/' file
Just for completeness, of course:
sed 'a peter' file
Is the obvious answer (see karakfa)!
Upvotes: 0
Reputation: 784898
Here is a simpler awk that uses a custom ORS
and works without matching any regex:
awk -v ORS='\npeter\n' '1' file
line1
peter
line2
peter
line3
peter
line4
peter
line5
peter
Upvotes: 1
Reputation: 212188
If you want to insert data before each line (as the question was originally), use i
:
$ yes | nl | sed 4q | sed -e 'i\
peter'
peter
1 y
peter
2 y
peter
3 y
peter
4 y
It's sometimes painful to keep track of which sed
allow you to skip the literal newline, but if you're using bash
you can also do: sed -e $'i\\\npeter'
Upvotes: 1
Reputation: 67467
although there is an accepted answer, for the record the right way to do it in sed
is not regex substitution, but using the append command
$ sed 'a peter' file
Upvotes: 3
Reputation: 1115
To add before each line:
$ echo "line1
line2
line3
line4
line5" | sed 's/^/peter\n/'
peter
line1
peter
line2
peter
line3
peter
line4
peter
line5
The sed script is fairly simple. It's a substitution command s/regex/replacement/
. In this case, the regex is just ^
, meaning "beginning of the line". And the replacement is peter
plus \n
, which is a newline special character.
So it reads like this:
before each line, insert "peter" plus a newline
To add after each line:
$ echo "line1
line2
line3
line4
line5" | sed 's/$/\npeter/'
line1
peter
line2
peter
line3
peter
line4
peter
line5
peter
Here, the script is similar except that the regex is $
, which means "end of the line", and the newline is substituted before peter
instead of after. It reads as follows:
after each line, add a newline and the word "peter"
Upvotes: 6
Reputation: 133428
Could you please try following.
awk '{print $0 ORS "peter"}' Input_file
Explanation: looks like OP changed samples so I changed it as per samples now. Simply printing current line with new line and string value peter then for each line of Input_file.
Upvotes: 4