處理數(shù)據(jù)的時候經(jīng)常遇到將多行fasta轉(zhuǎn)換為單行筝蚕,或者將很多行fasta串聯(lián)起來合并為一行卦碾,下面是一些方法。
vi test.fa
>a
AAAA
>b
CCCC
GGGG
>c
AAAA
GGGGG
CCCCCC
TTTTTTTT
目的文件:
>123
AGCTAGCTAAAA
>456
AAAATTTTCCCCAAAATTTTCCCC
或者
>a
AAAACCCCGGGGAAAAGGGGGCCCCCCTTTTTTTT
1起宽、將多行fasta轉(zhuǎn)換為單行的洲胖,并保留原來的頭
awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }' test.fa
>a
AAAA
>b
CCCCGGGG
>c
AAAAGGGGGCCCCCCTTTTTTTTTTTTTTTT
ps : /^>/ { print n $0; n = "" } : 讀取第一行時,因為n暫時不存在坯沪,所以不會出現(xiàn)第一行為空的情況
ps printf和print的區(qū)別:
printf不換行 print換行
2绿映、將多行fasta文件轉(zhuǎn)為單行,只保留一個頭
sed '1!{/^>/d;}' test.fa | awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }'
>a
AAAACCCCGGGGAAAAGGGGGCCCCCCTTTTTTTT
3屏箍、寫成一個小腳本
vi single_fa.sh
#! /bin/sh
func() {
echo "Usage:"
echo "single_fa.sh [-m mode(many or only)] [-n header name (if -m=only)] [-i input_file] [-o output_file]"
echo "MODE:"
echo "many: keep all header"
echo "only: keep single header"
exit -1
}
while getopts :m:n:i:o: varname
do
let optnum++
case $varname in
m)
mode="$OPTARG" ;;
n)
name="$OPTARG" ;;
i)
input="$OPTARG" ;;
o)
output="$OPTARG" ;;
?)
func ;;
esac
done
if [ $mode = "many" ];then
awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }' $input > $output
elif test "$name" ; then
sed '1!{/^>/d;}' $input | awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }' |sed "1i\>$name" > $output
else
sed '1!{/^>/d;}' $input | awk '!/^>/ { printf "%s", $0; n = "\n" } /^>/ { print n $0; n = "" } END { printf "%s", n }' > $output
fi
運行演示
sh single_fa.sh -m many -i test.fa -o output.fa
cat output.fa
>123
AGCTAGCTAAAA
>456
AAAATTTTCCCCAAAATTTTCCCC
sh single_fa.sh -m only -i test.fa -o output.fa
cat output.fa
>123
AGCTAGCTAAAAAAAATTTTCCCCAAAATTTTCCCC
sh single_fa.sh -m only -i test.fa -o output.fa -n hahaha
cat output.fa
>hahaha
AGCTAGCTAAAAAAAATTTTCCCCAAAATTTTCCCC
部分內(nèi)容參考自
https://stackoverflow.com/questions/15857088/remove-line-breaks-in-a-fasta-file
https://unix.stackexchange.com/questions/193246/how-can-i-detect-that-not-enough-options-were-passed-with-getopts