我正在嘗試用字母寫一個 shell 腳本,
我有 5 個這樣的引數
$alphametic 5790813 BEAR RARE ERE RHYME
要得到
ABEHMRY -> 5790813
我試過這個:
#!/bin/bash
echo "$2 $3 $4 $5" | sed 's/ //g ' | sed 's/./&\n/g' | sort -n | sed '/^$/d' | uniq -i > testing
paste -sd '' testing > testing2
sed "s|^\(.*\)$|\1 -> ${1}|" testing2
但我收到錯誤(使用最后一個命令sed),我不知道問題出在哪里。
uj5u.com熱心網友回復:
#!/bin/sh
val="$1"
shift
printf '%s' "$@" | tr '[:lower:]' '[:upper:]' | awk -v FS='' -v OFS='\n' '{$1=$1}1' | sort -n | uniq | tr -d '\n'
printf " -> %s\n" "$val"
編輯:輸出中的固定順序
shift$1從引數中洗掉。$@然后將包含除第一個之外的所有引數,然后舊的$2將是$1,$3將是$2,等等......printf '%s' "$@"將所有引數連接成一個字串tr [:lower:] [:upper:]將所有小寫字母轉換為其等效的大寫字母。awk -v FS='' -v OFS='\n' '{$1=$1}1'垂直輸出每個字符tr -d '\n'洗掉所有\n字符
uj5u.com熱心網友回復:
另一種方法:
chars=$(printf '%s' "${@:2}" | fold -w1 | sort -u | paste -sd '')
echo "$chars -> $1"
sort-n在這里沒有意義:這些是字母,而不是數字。
uj5u.com熱心網友回復:
awk用于整個事情的一個想法:
arg1="$1"
shift
others="$@"
awk -v arg1="${arg1}" -v others="${others}" '
BEGIN { n=split(others,arr,"") # split into into array of single characters
for (i=1;i<=n;i ) # loop through indices of arr[] array
letters[arr[i]] # assign characters as indices of letters[] array; eliminates duplicates
delete letters[" "] # delete array index for "<space>"
PROCINFO["sorted_in"]="@ind_str_asc" # sort array by index
for (i in letters) # loop through indices
printf "%s", i # print index to stdout
printf " -> %s\n", arg1 # finish off line with final string
}
'
注:需要GNU awk對PROCINFO["sorted_in"](到的索引排序letters[]陣列)
這會產生:
ABEHMRY -> 5790813
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368374.html
上一篇:如何使用“sed”或“awk”替換url引數查詢字串
下一篇:一號輸出
