1748285 Members
3945 Online
108761 Solutions
New Discussion юеВ

Insert blank line

 
george_57
Occasional Advisor

Insert blank line

Hi Experts,
Im trying to read a text file with 5 fields and insert a blank line after every two records or lines. Could somebody help me with a script to do read the file and insert a blank line after reading every 2 lines?
none
7 REPLIES 7
Christian Gebhardt
Honored Contributor

Re: Insert blank line

Hi george

awk '{line[NR]=$0}
END {
for ( i=1;i<=NR;i++)
{ print line[i]; if ( i%2 == 0 ) print}
}' textfile

textfile like this:

a1 a2 a3 a4 a5
b1 b2 b3 b4 b5
c1 c2 c3 c4 c5
d1 d2 d3 d4 d5
e1 e2 e3 e4 e5
f1 f2 f3 f4 f5

results in

a1 a2 a3 a4 a5
b1 b2 b3 b4 b5

c1 c2 c3 c4 c5
d1 d2 d3 d4 d5

e1 e2 e3 e4 e5
f1 f2 f3 f4 f5

Chris
john korterman
Honored Contributor

Re: Insert blank line

Hi George,
this should do what you want:

#!/usr/bin/sh
# insert blank after CH_NUMBER of lines
CH_NUMBER=2
NUMBER=0
cat $1 | while read line
do
if [ $NUMBER -eq $CH_NUMBER ]
then
echo ""
NUMBER=0
fi
let NUMBER="$NUMBER + 1"
echo $line
done

regards,
John K.
it would be nice if you always got a second chance
Leif Halvarsson_2
Honored Contributor

Re: Insert blank line

Hi

Another awk solution:

awk '{ getline a ; getline b ; print a",\n",b,"\n"}'
James R. Ferguson
Acclaimed Contributor

Re: Insert blank line

Hi George:

Another:

# awk '{if (NR%2==1) {print $0} else {print $0"\n"}}' filename

Regards!

...JRF...
Sachin Patel
Honored Contributor

Re: Insert blank line

Hi George

# add a blank line every 2 lines (after lines 2,4,6 etc.)
gsed '0~5G' # GNU sed only
sed 'n;G;' # other seds

sed 'n;G;' test > test1

Now test1 has blank line after ever 2 lines.


Sachin
Is photography a hobby or another way to spend $
Jordan Bean
Honored Contributor

Re: Insert blank line


This PERL gem works ($. is the input line #):

perl -ne 'print; print "\n" if $.%2==0;' file0 > file1

This following does NOT work because it prints the input line after the code snippit is processed:

perl -pe 'print "\n" if $.%2==0;' file0 < file1

Jordan Bean
Honored Contributor

Re: Insert blank line


A little more terse:

perl -ne 'print $_,($.%2)?undef:"\n";' outfile