私はBashスクリプトを学んでいますが、この問題で苦労しています。で複数の行が与えられたら、STDIN
まず長さに応じて昇順に並べ替えます。その後、同じ文字数を含む行がある場合、行に含まれる空白以外の文字数に基づいて昇順に並べ替えられます。
私はいくつかの異なるアプローチを試しましたが、通常はBashの珍しい特性に閉じ込められます。
これが私が今まで得たものです:
#!/bin/bash
sorted=()
while IFS='' read -r line; do
length=${#line}
if [[ ${sorted[$length]} == "" ]] ; then
sorted[$length]="$line"
else
#non unique length
#sorted[$length]="${sorted[$length]}\n$line"
IFS=$'\n' arr=("${sorted[$length]}")
arr+=("$line")
spaces=()
for ((i=0 ; i < ${#arr[@]} ; ++i )) ; do
spaces[$i]=$(echo "${arr[$i]}" | sed "s: : \n:g" | grep -c " ")
done
arr_sorted=()
for ((i =0 ; i < ${#spaces[@]} ; i++ )) ; do
for ((j=0 ; j < ${#arr[@]} ; i++ )) ; do
this_line_length=$(echo "${arr[$j]}" | sed "s: : \n:g" | grep -c " ")
if [[ "$this_line_length" == "${spaces[$i]}" ]] ; then
arr_sorted+=("${arr[$j]}")
unset arr[$j]
fi
done
done
sorted[$length]="${arr_sorted[@]}"
fi
done
私はこれが最善のアプローチから離れていると推測します。 bashの組み込み機能にあまり依存せず、すべてを実装しようとしましたが、今は意味がないようです。
ベストアンサー1
他の原則と同じ原則を使用します(空白文字の有無にかかわらず行の長さを取得し、整列してから削除します)awk
。
awk '{NC = length(gensub(/[[:space:]]/, "", "g")); print length, NC, $0}' file |
sort -nk1,2 |
sed -r 's/^([0-9]+ ){2}//'
gensub(/[[:space:]]/, "", "g")
行からすべての空白文字を削除すると、残りの文字列の長さが得られます。
コードブロックまでの質問テキストを使用し、幅は80文字に縮小されます。
$ awk '{NC = length(gensub(/[[:space:]]/, "", "g")); print length, NC, $0}' foo | sort -nk1,2 | sed -r 's/^([0-9]+ ){2}//'
increasing order).
Here's what I've got so far:
f the idiosyncrasies of bash.
iven a bunch of lines from STDIN, sort them first by the length of the line in i
I've tried this a couple of different ways but I usually get caught up in some o
, sort them by the number of nonblank characters contained in the lines (also in
I am working on learning bash scripting but I am struggling with this problem. G
ncreasing order. Then, if there are any lines with the same number of characters