Script to sort the files and append the extension .sort to the sorted version of the file

Hello all -
I am to this forum and fairly new in learning unix and finding some difficulty in preparing a small shell script. I am trying to make script to sort all the files given by user as input (either the exact full name of the file or say the files matching the criteria like all files having which starts with say ZEB*). Then script should find all those files based on matching criteria and append the extension .sort to the sorted version of the file whilst retaining the original version of the file. Script should not sort files in sub-directories, only the top level directory it is run from.
This piece of code line is working for me but it does sort all the files present in that path/location.

find * -prune -type f |grep -v .sort| while read file
do
sort "$file" > "$file".sort
done

I want some user friendly shell script which ask user to enter the path location where all files exists and than enter either the exact file name or pattern to search the files in that location and sort only on those files enter by user as input.

Kindly help me ..

The find command is unsuitable for what you are trying to do, plain shell expansion of the pattern (or * if no pattern) is a better option

#!/bin/bash

if [ "X$1" = "X" ]
then
   pattern='*'
else
   pattern="$1"
fi
for file in $pattern
do
   if [ -f $file ]
   then
      sort "$file" > "$file".sort
   fi
done

If that fails to work for you, perhaps you aren't quoting your pattern and as a result the expansion is happening outside your script'
ie. call it like so

bash ~/tmp/sorter.sh 'file*'

or in the case of your script above

find \* -prune -type f ......
1 Like

Hi Skrynesaver

I copied the code suggested by you but it actually sorting all the file and not asking user to enter specific file or file pattern and than sorting only those files. Can you pls amend the script so it sort only the selective files and not all placed in that location. Your help is much appreaciated.

As stated above. it takes a pattern as an argument and uses shell expansion to provide a list of filenames as the argument to the sort command in the for loop.
ie
sorter.sh '.txt'
or
sorter.sh \
.data

would use the pattern povided