京橋のバイオインフォマティシャンの日常

南国のビーチパラソルの下で、Rプログラムを打ってる日常を求めて、、Daily Life of Bioinformatician in Kyobashi of Osaka

Macでの圧縮・解凍コマンドをメモっておく件

はじめに

よく使う割にいつもネットで調べるはめになるので、、

このタイミングで、Mac Terminalでの圧縮と解凍コマンドをメモっておく*1

色々とデータ圧縮方式 / アーカイブ方式について、まとめてみました。

LINUX/Macの基本コマンドの関連記事

skume.net

skume.net

skume.net

skume.net

skume.net

skume.net

skume.net

.zip について

.zipは、Windowsでよく使用される、データ圧縮やアーカイブのフォーマットの1つである。

Macの場合、control + クリックで、「・・・を圧縮」という選択があって、zip圧縮できる。

ただ、zipコマンドでは、4GB以上のファイルが圧縮できないので、それ以上の容量のファイル圧縮には、.tar.gz形式などを使用する*2*3

いちおうコマンドだと、、、

zipコマンドによるzip圧縮
zip [File name]
unzipコマンドによるzip解凍
unzip [File name]

.tarについて

tar は、Tape Archival and Retrieval formatの略である。

.tar ファイルは、データ圧縮は行われておらず、複数のフォルダ・ファイルを1つにまとめられたアーカイブ・ファイルである*4

tarコマンドによるtarアーカイブ化(非圧縮)

「XXXX.tar」としてアーカイブ化する場合

tar -cvf XXXX.tar [File1] [File2] [File3] 

オプション

c: 新規作成(圧縮)する

v: 処理したファイルの一覧表示

f: 指定ファイルを使用する

[File1] [File2] [File3]: 圧縮したいファイル(フォルダも可)

tarコマンドによるtarアーカイブ解凍

「XXXX.tar」をアーカイブ解凍する場合

tar -xvf XXXX.tar

オプション

x: 解凍する

.gzについて

gzipコマンドによるgzip圧縮
gzip [File1]  

#OR

#inputファイルを残して、圧縮する場合
gzip -k [File1]  

複数のファイルを圧縮する場合

gzip [File1] [File2] [File3]  

この場合、それぞれ別のgzファイルとして保存される

つまり、gzipコマンドでは、ファイルの圧縮はできるが、 ファイルをまとめるアーカイブ化はできない。

gunzipコマンドで、gzip圧縮をもとに戻す

「XXXX.gz」を解凍する場合

gunzip XXXX.gz
#OR
gzip -d XXXX.gz

#inputファイルを残して、解凍する場合
gunzip -k XXXX.gz
#OR
gzip -d -k XXXX.gz

.tar.gzについて

.tar.gzとは、tarでアーカイブ化して、 gzip圧縮することを意味する。

tarコマンドによるtar.gz圧縮

「XXXX.tar.gz」として、tar.gz圧縮アーカイブ化する場合

tar -zcvf XXXX.tar.gz [File1] [File2] [File3]
#あるいは
tar acvf XXXX.tar.gz [File1] [File2] [File3]

オプション

z: gzipの意味

cvf: tarアーカイブ化

[File1] [File2] [File3]: 圧縮したいファイル(フォルダも可)

a: 拡張子による圧縮方式の自動判定

オプションの「-」: tarの場合、省略可

拡張子は、「.tar.gz」または「.tgz」が可

tarコマンドによるtar.gz解凍

「XXXX.tar.gz」をgzip解凍して、tarアーカイブを戻す場合

tar -zxvf xxxx.tar.gz
#あるいは
tar axvf xxxx.tar.gz

オプション

z: gzipの意味

xvf: tarアーカイブの解凍

a: 拡張子による圧縮方式の自動判定

オプションの「-」: tarの場合、省略可

拡張子は、「.tar.gz」または「.tgz」が可

.bz2について

bzip2コマンドで、bzip2圧縮ができる。

bzip2は、「gzip」よりも圧縮率が良いらしい。

bzip2コマンドによるbzip2圧縮
bzip2 -z [File1]  

-z: 圧縮を行う(デフォルトなので省略化)

※ フォルダごとの圧縮は不可

任意のファイル名保存で、bzip2圧縮を行う場合
bzip2 [File] > xxxx.bz2

bunzip2コマンドによるbzip2解凍

「XXXX.bz2」を解凍する場合

bunzip2 XXXX.bz2  
#あるいは(おそらく)
bzip2 -d XXXX.bz2 > [File]

#元ファイルを残して、解凍する場合
bunzip2 -k XXXX.bz2  

オプション

-d: 伸張を行う

.tar.bz2について

.tar.bz2とは、tarでアーカイブ化して、 bzip2圧縮することを意味する。

tarコマンドによるtar.bz2圧縮

「XXXX.tar.bz2」として、tar.bz2圧縮アーカイブ化する場合

tar -jcvf XXXX.tar.bz2 [File1] [File2] [File3]
#あるいは
tar acvf XXXX.tar.bz2 [File1] [File2] [File3]

オプション

j: bzip2の意味

cvf: tarアーカイブ化

[File1] [File2] [File3]: 圧縮したいファイル(フォルダも可)

a: 拡張子による圧縮方式の自動判定

オプションの「-」: tarの場合、省略可

※ フォルダごとの圧縮が可能

tarコマンドによるtar.bz2解凍

「XXXX.tar.bz2」をbz2解凍して、tarアーカイブを戻す場合

tar -jxvf xxxx.tar.bz2
#あるいは
tar axvf xxxx.tar.bz2

オプション

j: bzip2の意味

xvf: tarアーカイブの解凍

a: 拡張子による解凍方式の自動判定

オプションの「-」: tarの場合、省略可

.tar.xz について

.tar.xzとは、tarでアーカイブ化して、 xz圧縮することを意味する。

xz圧縮は、「gz」「bz2」よりも圧縮率が良いらしい。

tarコマンドによるtar.xz圧縮

「XXXX.tar.xz」として、tar.xz圧縮アーカイブ化する場合

tar -Jcvf XXXX.tar.xz [File1] [File2] [File3]
#あるいは
tar acvf XXXX.tar.xz [File1] [File2] [File3]

オプション

J: xzの意味、jの大文字

cvf: tarアーカイブ化

[File1] [File2] [File3]: 圧縮したいファイル(フォルダも可)

a: 拡張子による圧縮方式の自動判定

オプションの「-」: 省略可能

tarコマンドによるtar.xz解凍

「XXXX.tar.xz」をxz解凍して、tarアーカイブを戻す場合

tar -Jxvf xxxx.tar.xz
#あるいは
tar axvf xxxx.tar.xz

xz圧縮の意味

J: xzの意味

xvf: tarアーカイブの解凍

a: 拡張子による解凍方式の自動判定

オプションの「-」: 省略可能

まとめ

よくよく全体をまとめてみると、拡張子さえちゃんと決めてあげれば、「tar acvf」と「tar axvf」で、 ファイル圧縮・解凍は問題ないこと分かった。

補足

tarは何の略?

tar(ター)は、ファイルアーカイブのファイルフォーマットの一つで、tape archivesの略です。 また、このファイルフォーマットを処理するUNIXコマンドである、tarも意味します。

gzipは何の略?

gzip(ジー・ジップ)は、圧縮データのフォーマットあるいはデータ圧縮プログラムの1つで、「GNU zip」の略です。

参考資料

qiita.com

*1:LINUXでもだいたい同じコマンド

*2:個人的には、2GBを超えるファイルで、すでに使わない方が無難なようにも思う。

*3:最近、4GB以上のファイルが圧縮できる、ZIP64フォーマットもあるようだが、解凍ツールが対応してない時もあるようだ。。Macユーザーには無用な知識かと、、、

*4:tar コマンドで色々できてしまうのでややこしさがある・・・

【R言語】データサイズ・行数が異なるテキストファイルにおけるファイル読み込み関数の速度比較

はじめに

最近、数GBを超えるテキストデータを扱うようになり、今更ながら、Rのファイル読み込み関数の速度比較について一度検討してみた。

今回、以下の3つのファイル読み込み関数について調査してみた。

実行環境

macOS Catalina (10.15.4)
R version 3.6.3 (2020-02-29)

検証用のファイル生成

検証用のファイルとしては、適当な文字列が適当に改行されて、10億行くらいあるファイル(.txt あるいは.csv)が用意できればと考えている。

まず、文字列生成について調べてみた。最初に見つかったのが、opensslコマンドを使う方法である。

opensslコマンドを用いた、ランダム文字列の生成

ランダム文字列を生成する、opensslコマンドの基本文法としては以下のようだ。

openssl rand [進数] [任意のバイト数]

進数のオプション:

-hex : 16進数

-base64 : 64進数

実際に、opensslで文字列生成をやってると、

openssl rand -hex 10

3fd8220419ed7c62043c

openssl rand -base64 10

k/ROtoo/l2k7aw==

出力を見た感じ、Rで読み込むなら、-hex(16進数) が良さそうだ。

少し 長めの文字列も出力してみると

time openssl rand -hex 5000000 > test.txt

real    0m0.833s
user    0m0.812s
sys 0m0.017s

## ファイル内の文字数のカウント
wc -m test.txt

10000001 test.txt

## 1文字ずつで改行する
time fold -w 1 test.txt > testR.txt

real    0m1.315s
user    0m1.276s
sys 0m0.031s

testR.txtファイルで、約1000万文字(行)、20MBほどのファイルが生成できた。

ただ、これだと、生成速度が若干遅いので、別の方法も検討してみる。

echotrコマンドを用いた文字列の生成

echotrコマンドを組み合わせると、改行した文字列が作れるようだ。例えば、こんな感じ

echo 'helloworld'{1..5} | tr  ' ' '\n'

helloworld1
helloworld2
helloworld3
helloworld4
helloworld5

まぁ、いま思うと、連番の数字だけでも良いように思う。

'helloworld'を消して実行してみると

time echo {1..10000000} | tr  ' ' '\n' > test1.txt

real    0m22.817s
user    0m23.285s
sys 0m0.614s

## 行数をカウントしてみる
wc -l test1.txt

 10000000 test1.txt

1000万行、79MBほどのファイルが生成できた。

こっちも、生成に結構時間がかかる。

seqコマンドを用いた連番数字の生成

単純に、連番数字の生成の場合なら、seqというコマンドがあるようだ。

コマンドの文法もシンプルで良い。

seq 5

1
2
3
4
5

また、同じく連番数字で2000万行を生成してみたが、、結構速い。「echoとtr」よりも10倍くらい速い。

time seq 10000000 > test2.txt

real    0m2.297s
user    0m2.161s
sys 0m0.122s

wc -l test2.txt

 10000000 test2.txt

114MBほどのファイルが生成できた。

echotrコマンドの時より、ファイルサイズが大きいのが気がかりだが、とりあず速いので、seqコマンドでやってみる。

seqコマンドを用いた検証用ファイルの生成

以下、time seq [行数] > [ファイル名].txt コマンドで実行した結果である。

ファイル名 行数 サイズ(約) real時間
Seq01.txt 1000万 114MB 0m2.478s
Seq02.txt 2000万 233MB 0m4.548s
Seq04.txt 4000万 471MB 0m9.150s
Seq06.txt 6000万 708MB 0m13.319s
Seq08.txt 8000万 946MB 0m18.095s
Seq10.txt 1億 1.18GB 0m22.223s
Seq15.txt 1.5億 1.78GB 0m31.878s
Seq30.txt 3.0億 3.56GB 1m3.527s

検証用ファイルが生成できたところで、ようやくRでの読み込みをやってみる。まずは、、、

Rでのファイル読み込み検証

utils::read.table関数でのファイル読み込み

R上で、read.table関数で読み込んでみて、ちゃんと読み込めているかをしてみる。((いちおう、dim関数とtail関数で確かめた(省略)。))

## 有効数字の設定
options(digits=7)
## 指数表現の設定
options(scipen=100)

##読み込み実行

system.time(ur_Seq01 <- read.table("./Seq01.txt"))
#   ユーザ   システム       経過  
#    5.683      0.198      5.895 

system.time(ur_Seq02 <- read.table("./Seq02.txt"))
#   ユーザ   システム       経過  
#    8.641      0.312      8.991 

system.time(ur_Seq04 <- read.table("./Seq04.txt"))
#   ユーザ   システム       経過  
#    15.087      0.568     15.700 

system.time(ur_Seq06 <- read.table("./Seq06.txt"))
#   ユーザ   システム       経過  
#    22.121      0.840     23.085 

system.time(ur_Seq08 <- read.table("./Seq08.txt"))
#   ユーザ   システム       経過  
#    28.819      1.246     30.322 

system.time(ur_Seq10 <- read.table("./Seq10.txt"))
#   ユーザ   システム       経過  
#    35.568      1.343     37.051 
    
system.time(ur_Seq15 <- read.table("./Seq15.txt"))
#   ユーザ   システム       経過  
#    53.427      2.523     56.541 

system.time(ur_Seq30 <- read.table("./Seq30.txt")); tail(ur_Seq30, n=100)
#   ユーザ   システム       経過  
#   103.617      6.371    111.173

data.table::fread関数でのファイル読み込み

data.tableパッケージをインストールして、読み込む。

if(!require("data.table")){install.packages("data.table")}; library(data.table)

#要求されたパッケージ data.table をロード中です 
#data.table 1.12.8 using 4 threads (see ?getDTthreads).  Latest news: r-datatable.com

早速、fread関数を試してみる。

##読み込み実行

system.time(df_Seq01 <- fread("./Seq01.txt"))
#   ユーザ   システム       経過  
#     0.296      0.083      0.215 

system.time(df_Seq02 <- fread("./Seq02.txt"))
#   ユーザ   システム       経過  
#     0.513      0.163      0.406 
     
system.time(df_Seq04 <- fread("./Seq04.txt"))
#   ユーザ   システム       経過  
#     0.992      0.306      0.728 
     
system.time(df_Seq06 <- fread("./Seq06.txt"))
#  ユーザ   システム       経過  
#     1.507      0.502      1.081
     
system.time(df_Seq08 <- fread("./Seq08.txt"))
#   ユーザ   システム       経過  
#     2.133      0.790      1.533 

system.time(df_Seq10 <- fread("./Seq10.txt"))
#   ユーザ   システム       経過  
#     2.597      1.082      2.092 

system.time(df_Seq15 <- fread("./Seq15.txt"))
#   ユーザ   システム       経過  
#     3.779      1.961      4.028 

system.time(df_Seq30 <- fread("./Seq30.txt"))
#   ユーザ   システム       経過  
#     7.847      3.987      8.032

readr::read_csv関数でのファイル読み込み

readrパッケージをインストールして、読み込む。

if(!require("readr")){install.packages("readr")}; library(readr)

# 要求されたパッケージ readr をロード中です

read_csv関数を試してみる

##読み込み実行

system.time(rr_Seq01 <- read_csv("./Seq01.txt", col_names = F))
#   ユーザ   システム       経過  
#     1.208      0.078      1.290 
system.time(rr_Seq02 <- read_csv("./Seq02.txt", col_names = F))
#   ユーザ   システム       経過  
#     2.797      0.310      3.717 
     
system.time(rr_Seq04 <- read_csv("./Seq04.txt", col_names = F))
#   ユーザ   システム       経過  
#     5.614      0.588      7.349 
     
system.time(rr_Seq06 <- read_csv("./Seq06.txt", col_names = F))
#   ユーザ   システム       経過  
#     8.425      0.819     11.102 
     
system.time(rr_Seq08 <- read_csv("./Seq08.txt", col_names = F))
#   ユーザ   システム       経過  
#    11.244      1.147     14.760 

system.time(rr_Seq10 <- read_csv("./Seq10.txt", col_names = F))
#   ユーザ   システム       経過  
#    13.981      1.973     21.484 

system.time(rr_Seq15 <- read_csv("./Seq15.txt", col_names = F))
#   ユーザ   システム       経過  
#    21.906      3.270     32.043 

system.time(rr_Seq30 <- read_tsv("./Seq30.txt", col_names = F))
#   ユーザ   システム       経過  
#    43.632      6.119     63.369 

速度比較の結果

ファイルサイズ、読み込み速度の結果を関数ごとにまとめてみる。

ファイル名 行数 サイズ(約) read.table fread read_csv
Seq01.txt 1000万 114MB 5.895 0.215 1.290
Seq02.txt 2000万 233MB 8.991 0.406 3.717
Seq04.txt 4000万 471MB 15.700 0.728 7.349
Seq06.txt 6000万 708MB 23.085 1.081 11.102
Seq08.txt 8000万 946MB 30.322 1.533 14.760
Seq10.txt 1億 1.18GB 37.051 2.092 21.484
Seq15.txt 1.5億 1.78GB 56.541 4.028 32.043
Seq30.txt 3.0億 3.56GB 111.173 8.032 63.369

速度比較結果のplotlyグラフ

比較結果をplotlyグラフにしてみる。

## データセットの作成
data <- matrix(c(0.114, 5.895, 0.215, 1.290,
                 0.233, 8.991, 0.406, 3.717,
                 0.471, 15.700, 0.728, 7.349,
                 0.708, 23.085, 1.081, 11.102,
                 0.946, 30.322, 1.533, 14.760,
                 1.18,  37.051, 2.092, 21.484,
                 1.78,  56.541, 4.028, 32.043,
                 3.56,  111.173, 8.032, 63.369),
                 ncol = 4, byrow = T)

## データフレームへの変換、行列に名前をつける
data.df <- data.frame(data)
colnames(data.df) <- c("size", "read.table", "fread", "read_csv")
rownames(data.df) <- 1:nrow(data.df)
data.df

#  size read.table fread read_csv
#1     0.114      5.895 0.215    1.290
#2     0.233      8.991 0.406    3.717
#3     0.471     15.700 0.728    7.349
#4     0.708     23.085 1.081   11.102
#5     0.946     30.322 1.533   14.760
#6     1.180     37.051 2.092   21.484
#7     1.780     56.541 4.028   32.043
#8     3.560    111.173 8.032   63.369

## plotlyのインストール
if(!require("plotly")){install.packages("plotly")}; library(plotly)

#plotlyで、マーカー + 折れ線グラフをつくる
fig <- plot_ly(data.df, x = ~size, )
fig <- fig %>% add_trace(y = ~read.table, name = 'read.table', mode = 'lines+markers')
fig <- fig %>% add_trace(y = ~fread, name = 'fread', mode = 'lines+markers')
fig <- fig %>% add_trace(y = ~read_csv, name = 'read_csv', mode = 'lines+markers')
fig <- fig %>% layout(xaxis = list(title = 'File size (GB)'), yaxis = list(title = 'Reading time (sec)'))
fig
20200528071149
ファイル読み込み速度の関数比較

オリジナルHTML図 http://kumeS.github.io/Blog/readingTime/readingTime.html

結果

速いとは聞いていたが、ダントツで、freadでのファイル読み込みが速かった。

補足

読み込みデータフレームの有効数字6桁問題

> ur_Seq01 <- read.table("./Seq01.txt"); tail(ur_Seq01, n=30)

               V1
9999971   9999970
9999972   9999970
9999973   9999970
9999974   9999970
9999975   9999980
9999976   9999980
9999977   9999980
9999978   9999980
9999979   9999980
9999980   9999980
9999981   9999980
9999982   9999980
9999983   9999980
9999984   9999980
9999985   9999980
9999986   9999990
9999987   9999990
9999988   9999990
9999989   9999990
9999990   9999990
9999991   9999990
9999992   9999990
9999993   9999990
9999994   9999990
9999995  10000000
9999996  10000000
9999997  10000000
9999998  10000000
9999999  10000000
10000000 10000000


> df_Seq01 <- fread("./Seq01.txt"); tail(df_Seq01, n=30)

         V1
 1:  9999970
 2:  9999970
 3:  9999970
 4:  9999970
 5:  9999980
 6:  9999980
 7:  9999980
 8:  9999980
 9:  9999980
10:  9999980
11:  9999980
12:  9999980
13:  9999980
14:  9999980
15:  9999980
16:  9999990
17:  9999990
18:  9999990
19:  9999990
20:  9999990
21:  9999990
22:  9999990
23:  9999990
24:  9999990
25: 10000000
26: 10000000
27: 10000000
28: 10000000
29: 10000000
30: 10000000
          V1
          
> rr_Seq01 <- read_csv("./Seq01.txt", col_names = F); tail(rr_Seq01, n=30)

# A tibble: 30 x 1
        X1
     <dbl>
 1 9999970
 2 9999970
 3 9999970
 4 9999970
 5 9999980
 6 9999980
 7 9999980
 8 9999980
 9 9999980
10 9999980
# … with 20 more rows

3つの関数の出力とも、一の位が丸まってるので、Rの問題なんだろうか。R version 3.6.3 (2020-02-29)を使ってるのでバージョンの問題なのか。

数字の連番なら、行名を入れればよさそうだけど、、、とりあえず、この問題は今回スキップすることにした。

R上の全てのデータ・変数を消すコマンド

rm(list=ls())

ベクトルのメモリを使い切りましたへの対応

これは、今回でたエラーメッセージである。

エラー:  ベクトルのメモリを使い切りました (上限に達した?) 
Timing stopped at: 0.165 0.002 0.167

これが出てしまう場合は、

cd ~
echo "R_MAX_VSIZE=100Gb" >> .Renviron

と設定すると、ベクトルサイズの上限を変更できる。 実メモリと関係なく、上限メモリを設定するので良いらしい。

また、Rセッションでこの変更を行うには

## 上限32GBの設定
Sys.setenv('R_MAX_VSIZE'=32000000000)

で可能のようだ。

参考文献

www.it-swarm.dev

初心者向け ソフトウェア開発プラットフォーム GitHub API( git & gist コマンド )の使い方入門

master => main に変更されたみたい(11 Feb 2021)

はじめに

GitHub は、ソフトウェア開発のプラットフォームである。また、ソフトウェア開発者のみならず、ソフトウェア・ユーザーにとっても、ほぼ必須といえる、コード共有のコミュニティでもある。

GitHubリポジトリにアクセスする際のAPIである git コマンド、手軽にコード公開・ファイル公開ができる gist サービスのAPI gist コマンドについて、それぞれのインストールから、実際の使い方までをまとめてみた。

GitHubは少しの間やらないと、すぐにコマンドを忘れてしまうのは困ったものだ、、、

実行環境

macOS Catalina (10.15.4)
MacBook Pro (12-inch, 2019, Four Thunderbolt 3 ports)

git のインストールとログイン

当然、事前に、GitHubのアカウントを持っているのが前提。

gitのインストール・コマンドの実行

いつもの、brew コマンドを使う。

#gitのインストール
brew install git

#パス確認
which git

#バージョン確認
git --version

はじめの設定

git config --global user.name "アカウント名"
git config --global user.email "登録メールアドレス"
git config --global color.ui auto

#設定の表示
git config -l
#credential.helper=osxkeychain
#user.name=アカウント名
#user.email=登録メールアドレス
#color.ui=auto

git をインストールした際に、git-credential-osxkeychainが自動的にインストールされるようで、user.name、user.emailを設定した後に、git config -lさえすればパスワード設定がされて、git コマンドが使える。

以下のコマンドでも同じ情報が確認できる。

#コンフィグの表示
cat .gitconfig


[user]
    name = アカウント名
    email = 登録メールアドレス
[color]
    ui = auto
[credential]
    helper = osxkeychain

ここから実際にgit APIを使っていくが、初めての時も久々の時も、git コマンドで何をやっているかイメージしづらい。 そのため、以下のイメージ画像を見ながら、実際のコマンド操作をやるとイメージしやすいだろう。

git コマンドで何をやっているかのイメージ

他の記事とかを読んでいると、やり方は、大別して2パターンある

(1)ローカルフォルダ作成からやる場合

(2)GitHubリモートリポジトリを作成してからやる場合

個人的には(2)推奨なのだが、いちおう、両方とも説明することにする。

gitコマンドの使い方

(1)ローカルフォルダ作成からやる場合

まず、任意の作業フォルダを作成して、フォルダ内に移動する。

mkdir [ Your local git directory ]

cd [ Your local git directory ]

1. ローカルリポジトリの初期化

git init

## 確認しておく
ls -a
git config -l
git status

ls -aで、.git ファイルが表示されるはず。

2. .md/code などを作成・編集する

echo "# XXXX" >> README.md

ReadMeを作成する。 ここで、coding、各種ファイルの準備を行う。

3. インデックスへの変更ファイルの追加

git add -A

-A: git add . & git add -u を実行するオプション

4. ローカルリポジトリにファイル登録・コメント付与

git commit -m " 任意のコメント "

当分、2-4の繰り返し・・・

5. このタイミングで、新規のリモートリポジトリを作成しておく

GitHubサイトの右上の +New repository で作成する。

6. ローカルとリモートリポジトリの関連付け

git remote add origin https://github.com/[ Your user name ]/[ Your repository name ].git

git remote -v

7. 更新ファイルをリモートリポジトリに送る

git push origin main

-u: 変更されたファイルを追加するオプション

8. リモートリポジトリが更新された場合に、変更を取得してローカルに反映する

git pull

(2)GitHubリモートリポジトリを作成してからやる場合

この場合には、リモートリポジトリをローカル環境に git cloneして、git addgit commitgit pushする。

まずは、作業ディレクトリを作成して、フォルダ内に移動する。

mkdir [ The new directory ]

cd [ The new directory ]

1. リモートリポジトリをローカルに複製して、フォルダ内に移動する。

git clone https://github.com/[ Your user name ]/[ Your repository name ].git

cd [ Your repository name ]

git remote -v

2. .md/code などを作成・編集する

3. インデックスへの変更ファイルの追加

git add -A

4. ローカルリポジトリにファイル登録・コメント付与

git commit -m " 任意のコメント "

5. 更新ファイルをリモートリポジトリに送る

git push origin main

6. リモートリポジトリが更新された場合に、変更を取得してローカルに反映する

git pull

これで、git コマンドの一連の使い方は終わりです。 ブランチ管理がしたいとかも含めて、他にも、git branchgit checkoutgit rmgit resetgit revertgit mergegit rebasegit loggit diffgit fetch とかの git コマンドがあるので、 必要に応じて使いましょう。

.DS_Storeに関する補足

Macだと、ls -aでみると、.DS_Storeがあがっているとカッコ悪かったりする。 これは、Macが自動的に生成するシステム情報ファイルで、特に不要なので、

du -a | grep .DS_Store | xargs rm -rf

で、.DS_Storeを消しておきましょう。

GitHubでの personal access token(パーソナルアクセストークン)の設定

昨年くらいから、APIでのパスワード利用ができなくなっています。 そのため、アクセストークンを設定する必要があります。

GitHubのDeveloper settingsにアクセストークンを発行するページ( https://github.com/settings/tokens )があります。 今回は、Tokens (classic)で作成しています。

ここで、「Generate new token (classic)」を選択します。

そのページで、各種の設定を行い、「Generate token」でトークンが発行されるので、それをコピーします。

「git clone [あるリポジトリ].git」でリポジトリをダウンロードすると、そのフォルダ内に、configファイル( .git/config )があります。そのconfigファイルを開けます。

#該当フォルダに移動して、開く
open .git/config 

#ファイルを表示される場合
cat .git/config 

以下のようなファイルになっています。

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/[Your GitHub Name]/[Repo Name].git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
    remote = origin
    merge = refs/heads/main
[pull]
    rebase = false

8-9行目の「[remote "origin"] url = 」のところの設定を書き換えます。

[remote "origin"]
    url = https://github.com/[Your GitHub Name]/[Repo Name].git

↓↓↓↓↓

[remote "origin"]  
    url = https://[Your GitHub Name]:[Personal access tokens]@github.com/[Your GitHub Name]/[Repo Name].git

という感じに修正します。

具体的に、kumeSのagGraphSearchリポジトリであれば、以下のように記述します。

url = https://kumeS:ghp_XXXXXXXXXXXX@github.com/kumeS/agGraphSearch.git

また、以下のサイトも参考になります。

qiita.com

stackoverflow.com

gistのインストールとログイン

gistのインストール・コマンドの実行

brew install gist

which gist
#/usr/local/bin/gist

brewコマンドでいっぱつで入る。

GitHubアカウントへのログイン*1

gist --login

Obtaining OAuth2 access_token from GitHub.
GitHub username: [Type Your username]
GitHub password: [Type Your PW]
Success! https://github.com/settings/tokens

うまくいっていければ、HOMEディレクトリ .gistにアクセストークンが作成される。

当然、事前に、GitHubのアカウントを持っているのが前提。

gistコマンドの使い方

Step 01 ファイルのアップロード

基本形

gist -d "・・・" [File path] -f [Other name] 
  • -f : 別名を付けて、アップロードする
  • -d : 説明"・・・"の追記

基本形2 アップロード後すぐに、URLを開きたい場合

gist -o -d "・・・" [File path] -f [Other name] 
  • -o : ブラウザでURLを開く

Step 02 gistの一覧表示 & ファイルIDを調べる

自分のgistの一覧表示は、-lオプションで行う。

gist -l

gistのファイルごとのIDは、gist -l で出力される英数字の文字列を指す。 例えば、https://gist.github.com/ 8c49fc30f5b01ab8a5219343c9820063 の部分

(補足)他人のgistの一覧表示 は、gist -l USER_ID で行う。

Step 03 ファイルをUpdate(更新)する場合

基本形1

gist -u [URL or ID] [File path]

ただ、ローカルのファイル名とGistのファイル名が違う場合には

基本形2

gist -u [URL or ID] [File path] -f [The File name to replace]

大体の場合、こっちになると思う。 [URL or ID]については、例えば、 URLの場合、https://gist.github.com/ 8c49fc30f5b01ab8a5219343c9820063 あるいは、IDの場合、8c49fc30f5b01ab8a5219343c9820063 と表記する。

補足

gistコマンド実行のバッチファイル

毎回修正後のファイルをコマンドでアップロードするのも面倒なので、 コマンド実行のバッチファイルを作っていもいいかもしれない。

テキストエディターで、例えば、GIST.command とかいうファイルを作成する。 そこに、以下のコマンドを書いておく。

#!/bin/bash

MY_DIRNAME=$(dirname $0)
cd $MY_DIRNAME

gist -u [gist ID] -o [アップロードするファイル名] -f [gist上にアップロード済みのファイル名]

exit

次に、chmod +x GIST.commandで実行権限を与えておく。 そうすれば、commandダブルクリックでファイルをアップロードして、ウェブページも開いてくれる。

GitHubリポジトリをローカル環境にクローンする

gitコマンドの基本は、git cloneだろう。これでほしいリポジトリがダウンロードできる。

git clone [ `GitHubリポジトリのhttps URL (.git)` ] [ 任意のフォルダ名(省略可) ]

例えば、アノテーションツールである labelme-Image Polygonal Annotation with Python- をクローンする場合。

git clone https://github.com/wkentaro/labelme.git LabelME

作業ディレクトのLabelMEフォルダ内にダウンロードされるはず。 例えば、私が作成している、DLに関するリファレンス集であれば、

git clone https://github.com/kumeS/DLimageSegmentation

R上で実行する場合の命令文

Rを使っていると、ターミナルを立ち上げてというのも面倒になり、 Rからgit・gistコマンドをやりたくなる。その場合には、

system( 'gist -d "・・・" [File path] -f [Other name]' )

と、system( '...' ) or system( "..." ) 内にgit & gist コマンドを記述して、 R上で打てば良い。

git コマンドのヘルプ

git --help

usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone             Clone a repository into a new directory
   init              Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add               Add file contents to the index
   mv                Move or rename a file, a directory, or a symlink
   restore           Restore working tree files
   rm                Remove files from the working tree and from the index
   sparse-checkout   Initialize and modify the sparse-checkout

examine the history and state (see also: git help revisions)
   bisect            Use binary search to find the commit that introduced a bug
   diff              Show changes between commits, commit and working tree, etc
   grep              Print lines matching a pattern
   log               Show commit logs
   show              Show various types of objects
   status            Show the working tree status

grow, mark and tweak your common history
   branch            List, create, or delete branches
   commit            Record changes to the repository
   merge             Join two or more development histories together
   rebase            Reapply commits on top of another base tip
   reset             Reset current HEAD to the specified state
   switch            Switch branches
   tag               Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
   fetch             Download objects and refs from another repository
   pull              Fetch from and integrate with another repository or a local branch
   push              Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept.
See 'git help git' for an overview of the system.

gist コマンドのヘルプ

gist -h

Usage: gist [-o|-c|-e] [-p] [-s] [-R] [-d DESC] [-u URL]
                          [--skip-empty] [-P] [-f NAME|-t EXT]* FILE*
       gist --login
       gist [-l|-r]

        --login                      Authenticate gist on this computer.
    -f, --filename [NAME.EXTENSION]  Sets the filename and syntax type.
    -t, --type [EXTENSION]           Sets the file extension and syntax type.
    -p, --private                    Makes your gist private.
        --no-private
    -d, --description DESCRIPTION    Adds a description to your gist.
    -s, --shorten                    Shorten the gist URL using git.io.
    -u, --update [ URL | ID ]        Update an existing gist.
    -c, --copy                       Copy the resulting URL to the clipboard
    -e, --embed                      Copy the embed code for the gist to the clipboard
    -o, --open                       Open the resulting URL in a browser
        --no-open
        --skip-empty                 Skip gisting empty files
    -P, --paste                      Paste from the clipboard to gist
    -R, --raw                        Display raw URL of the new gist
    -l, --list [USER]                List all gists for user
    -r, --read ID [FILENAME]         Read a gist and print out the contents
        --delete [ URL | ID ]        Delete a gist
    -h, --help                       Show this message.
    -v, --version                    Print the version.

参考資料

www.wakuwakubank.com

qiita.com

qiita.com

*1:どうも、--loginコマンドでtokenが生成されるのは2020年末で廃止になるらしい。 We will remove the Authorizations API endpoint on November 13, 2020. If you accessed the API via password authentication, then we recommend you use the web flow to authenticate.