我ascii在一個目錄中有很多檔案,我只想按數字對檔案名進行排序并想并排粘貼。其次,粘貼后我想通過在末尾附加零來制作所有長度相同的列。
我的檔案被命名為
data_Z_1 data_N_457 data_E_45
1.5 1.2 2.3
2.0 2.3 1.8
4.5
起初我只想按照下面給出的數字對上面的檔案名進行排序,然后想并排粘貼為
data_Z_1 data_E_45 data_N_457
1.5 2.3 1.2
2.0 1.8 2.3
4.5
其次,我需要在粘貼的檔案中使所有列的長度相等,以便輸出應該像
1.5 2.3 1.2
2.0 1.8 2.3
0.0 0.0 4.5
I tried as below:
ls data_*_* | sort -V
但它不起作用。任何人都可以幫助我克服這個問題。提前致謝。
uj5u.com熱心網友回復:
請您嘗試以下操作:
paste $(ls data* | sort -t_ -k3n) | awk -F'\t' -v OFS='\t' '
{for (i=1; i<=NF; i ) if ($i == "") $i = "0.0"} 1'
輸出:
1.5 2.3 1.2
2.0 1.8 2.3
0.0 0.0 4.5
sort -t_ -k3n將欄位分隔符設定為_第 3 個欄位值并按數字對檔案名進行排序。-F'\t' -v OFS='\t'awk 命令的選項將輸入/輸出欄位分隔符分配給制表符。- awk 陳述句
for (i=1; i<=NF; i ) if ($i == "") $i = "0.0"掃描輸入欄位并設定0.0空欄位。 - final
1相當于print $0列印欄位。
[編輯]
如果你有大量的檔案,它可能會超過 bash 的能力。這是python使用dataframe.
#!/usr/bin/python
import glob
import pandas as pd
import re
files = glob.glob('data*')
dfs = [] # list of dataframes
for f in files:
df = pd.read_csv(f, header=None, names=[f]) # read file and assign column
num = re.sub(r'.*_', '', f) # extract number of the file
df.loc[-1] = [num] # insert the number in the first row
df.index = df.index 1 # adjust the index
df = df.sort_index()
df = df.apply(pd.to_numeric, errors='coerce') # force the cell values to floats
dfs.append(df) # add as a new column
df = pd.concat(dfs, axis=1, join='outer') # create a dataframe from the list of dataframes (equivalent of "paste")
df = df.fillna(0) # fill empty cells with 0
df.sort_values(by=0, axis=1, inplace=True) # sort by the file number
df= df.drop(0, axis=0) # remove the row of file number
print(df.to_string(index=False, header=False)) # print the dataframe removing index and header
這將產生相同的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350289.html
上一篇:PythonDjangoImportError:無法從“typing_extensions”匯入名稱“Required”
