Dear all,
I have a file like this:
imput
scaffold_0 1
scaffold_0 10000
scaffold_0 20000
scaffold_0 25000
scaffold_1 1
scaffold_1 10000
scaffold_1 20000
scaffold_1 23283
and I want the output like this:
scaffold_0 1 scaffold_0 10000
scaffold_0 10000 scaffold_0 20000
scaffold_0 20000 scaffold_0 25000
scaffold_0 25000 scaffold_1 1
scaffold_1 1 scaffold_1 10000
scaffold_1 10000 scaffold_1 20000
scaffold_1 20000 scaffold_1 23283
NOTE: I want the columns separated by tab
In other words, I want to combine
line 1 with line 2
line 2 with line3
line 3 with line4
....
I have this script:
while read line1
do
read line2
echo $line1 $line2
done < imput
But the results is:
scaffold_0 1 scaffold_0 10000
scaffold_0 20000 scaffold_0 25000
scaffold_1 1 scaffold_1 10000
scaffold_1 20000 scaffold_1 23283
so the script read line 1 and line 2, combine them, but do not follow reading the line 2 and combining with line 3. The script like jump the line 2 and follow the combination of line 3 and line 4 and again jump the next line (line 4).
How can I fix this script?
Best regards.
Could I suggest something like:-
prev=""
while read line
do
if [ "$prev" != "" ]
then
echo "$prev\t$line"
fi
prev="$line"
done < imput
The plan here being that for each line, you echo the previous line and the current read line, except for the first line read (where there is no previous)
I hope that this helps
Robin
Liverpool/Blackburn
UK
1 Like
Try:
{ read line1
while read line2
do
printf "%s\t%s\n" "$line1" "$line2"
line1=$line2
done
} < imput
Yes, that's neater. Sorry for being a fool and adding an if that will cost CPU especially for a large file. I wasn't thinking. :o
Robin
Hi,
another way;
cat YUORFILE.txt | awk -F" " '{ if ( FNR == 1 ) {a=$0;getline} ; {print a"\t"$0;a=$0} }'
1 Like
Thanks Robin, It is nice to have smart guys like you in computer.
I'm a newbie in programming, in fact I'm a biologist that is entering in bioinformatics.
So I have two question,
when I insert
prev=""
while read line do
is it meaning that the prev="" will be the current line when the loop start?
The condition:
if [ "$prev" != "" ]meaning what?
Sorry to disturb your work.
Best regards.
@Robin, your suggestion look fine, I think it is more a matter of preference. Not every echo interprets a \t
like that btw...