参考链接:
平时对于文本处理,可以选择sed,grep ,复杂一点awk ,再复杂一些哟Python. python 和linux 一样,也可以支持单行命令来操作!格式:
python -c
## -c cmd : program passed in as string (terminates option list)
## terminates option list 表示 -c 之后的其它选项不起作用,为终极选项
-c 之后,要用双引号将命令包起来,import 以;结尾,命令用[]括起来,多行命令用多个[]。
第一个例子:不区分单双引号
(base) [09:59:01] kcao@localhost:~
$ python -c "print('hello world')"
hello world
(base) [09:59:01] kcao@localhost:~
$ python -c 'print("hello world")'
hello world
接受echo 输入流;
必须加上read方法,sys.stdin 和f=open("...","r") 一样,需要f.read() 才可以读取文件内容.
$ echo "ck" |python -c "import sys;print(sys.stdin)"
$ echo "ck" |python -c "import sys;print(sys.stdin.read())"
ck
读取文件,计算fa文件的G碱基数目
$ cat > test.fa
>chr_1
ATCGTCGaaAATGAANccNNttGTA
AGGTCTNAAccAAttGggG
>chr_2
ATCGAATGATCGANNNGccTA
AGGTCTNAAAAGG
>chr_3
ATCGTCGANNNGTAATggGA
AGGTCTNAAAAGG
>chr_4
ATCGTCaaaGANNAATGANGgggTA
python 单行命令,调用Biopython包
$ cat test.fa |python -c "import sys;from Bio import SeqIO;[print(seq_record.id,seq_record.seq.count('G')) for seq_record in SeqIO.parse(sys.stdin,'fasta')]"
chr_1 8
chr_2 8
chr_3 8
chr_4 4
类似grep 操作,输出大于号的行.
$ cat test.fa | python -c "import sys,re;[sys.stdout.write(line) for line in sys.stdin if re.search('>', line)]"
>chr_1
>chr_2
>chr_3
>chr_4
类似sed 操作. 去掉>chr_.
$ cat test.fa | python -c "import sys,re;[sys.stdout.write(re.sub('>chr_', '', line)) for line in sys.stdin]"
1
ATCGTCGaaAATGAANccNNttGTA
AGGTCTNAAccAAttGggG
2
ATCGAATGATCGANNNGccTA
AGGTCTNAAAAGG
3
ATCGTCGANNNGTAATggGA
AGGTCTNAAAAGG
4
ATCGTCaaaGANNAATGANGgggTA