Reputation: 119
I have the below code, list of string that I'd like to sort.
LIST="APP_PATH_10_TARGET APP_PATH_1_TARGET APP_PATH_2_TARGET APP_PATH_3_TARGET"
My goal is to sort it into:
"APP_PATH_1_TARGET APP_PATH_2_TARGET APP_PATH_3_TARGET APP_PATH_10_TARGET"
So I did this:
SORTEDLIST=$(echo ${LIST} | sort -t"_" -k3n,3)
But its still showing:
SORTEDLIST=APP_PATH_10_TARGET APP_PATH_1_TARGET APP_PATH_2_TARGET APP_PATH_3_TARGET
I can't find out why the sort doesn't work.
================================================================
Update: This is the code that I'm working on.
I have this ENV variables:
APP_PATH_1_TARGET="/prd/example/1"
APP_PATH_2_TARGET="/prd/example/2"
APP_PATH_3_TARGET="/prd/example/3"
APP_PATH_10_TARGET="/prd/example/4"
The code that doesn't work, because the list is not in expected sequence:
create_app_dir(){
# Get all variables with name starts with APP_PATH*
local PARAMLIST=`echo ${!APP_PATH*}`
echo "PARAMLIST=${PARAMLIST}"
local SORTEDLIST=$(sort -t_ -k3n <<< ${PARAMLIST// /$'\n'}|tr -s "\n" " ")
echo "SORTEDLIST=${SORTEDLIST}"
# Iterate the list and create dir if doesn't exist
for p in ${SORTEDLIST}; do
if [[ "${p}" = *_TARGET ]] && [ ! -d "${p}" ]; then
echo "[+] Creating application directory:${!p}"
./make_dir.sh "${!p}"
if [ $? -ne 0 ]; then
echo "[-] Error: Unable to create dir." >&2
return 1
fi
fi
done
}
Upvotes: 0
Views: 408
Reputation: 30762
sort
arranges lines in order. To sort words, you want to re-write each word as a line:
SORTEDLIST=$(printf "%s\n" $LIST | sort -t_ -k3n)
Since you're using Bash, you'd be better using a real list, so that you can get the quoting right:
LIST=(APP_PATH_10_TARGET APP_PATH_1_TARGET APP_PATH_2_TARGET APP_PATH_3_TARGET)
SORTEDLIST=($(printf "%s\n" "${LIST[@]}" | sort -t_ -k3n))
for p in "${SORTEDLIST[@]}"
Also, you should avoid using all-uppercase for your shell variables; this convention is used to indicate environment variables intended to change program behaviour.
Upvotes: 0
Reputation: 1079
Try This:
SORTEDLIST = $(sort -t_ -k3n filename | tr -s '\n\r' ' ')
or
SORTEDLIST = $(sort -t_ -k3n filename | tr -s '\n' ' ')
Upvotes: 0
Reputation: 3141
Because sort is only working with lines by definition. man sort:
sort - sort lines of text files
SORTEDLIST=$(sort -t"_" -k3n,3 <<< ${LIST// /$'\n'}|tr -s "\n" " ")
Upvotes: 3