简体   繁体   中英

Sorting a list in bash

I have a problem with sorting a list. I think its the way how I put the strings together. But lets see the details:

I have large (windows)-txt-files. These are Readmes for a hotfixes. I want to extract the HotFix-Number with the Issue, which are solved in this release, like this:

1378 Issue: Here is the issue that is fixed
1390 Issue: Another issue is fixed
1402 Issue: Yet another fixed issue

I have a loop which calculates one file after another. In this loop, after some extract-operations I have 1 string-variable for the HotFix-Number and tmp4.txt with the text belonging to the HotFix-Number.

$NR=1378
cat tmp4.txt - Output: Issue: Here is the issue that is fixed

At the end of the loop I put these 2 components together:

array[IDX]=$(echo $NR $(cat tmp4.txt));

After the loop ended, I checked the content of each index. If I echo the single items, I get the correct form:

echo ${array[0]} #output: 1390 Issue: Another issue is fixed
echo ${array[1]} #output: 1378 Issue: Here is the issue that is fixed
echo ${array[2]} #output: 1402 Issue: Yet another fixed issue
...    

But when I want to sort the list with

for j in ${array[@]}; do echo "$j"; done | sort -n >> result.txt;

I get a file where all single words are sorted alphabetical. But I just want to refer to the HotFix-Number.

# Sampleoutput from result.txt for these 3 examples
Another
another
fixed
fixed
fixed
Here
...
Yet
1378
1390
1402

You need to add quotes around ${array[@]} , like this:

for j in "${array[@]}"; do echo "$j"; done | sort -n >> result.txt;

That will prevent bash reinterpreting the spaces inside your array entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM