Write an alias to search a file for a specific term car and
Write an alias to search a file for a specific term (car) and sort the output by string length.
(Include the shell code to produce the results). In your answers show a specific example which demonstrates that your script works as desired.
Update: This could be done in any language, maybe Java or C++
Solution
--------save the file as SortTheFile.java-------------------------------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class SortTheFile{
public static void main(String args[]) {
//initialise the array list to store the strings dynamically
List<String> lines = new ArrayList<>();
File file = new File(\"G://Student.txt\");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.compareTo(\"car\")>=0)
{
//compare the string if it has a word car and put it to list
lines.add(line);
} else
{
}
}
} catch(FileNotFoundException e) {
//print error if the file is not found
System.out.println(\"File not found\");
}
//pass the list to sort...
SortByLength(lines);
}
static void SortByLength(List lines) //Sorting the list by using comporator
{
Collections.sort(lines, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o1).length() - ((String)o2).length() ;
}
});
for(int i=0;i<lines.size();i++)
{
System.out.println(lines.get(i));
}
}
}
------------------------------------------Examplle data of the file and output---------------------------
data:---------------
gsas sajgsa car
hgafscar hjagdjggds samhgcar
ghashas car
ascaiiiiiiiiiiiiiiir
xcar
disduyuucarsdy
cardf
jasghhhhhhhhhhgajgjashjahhagshgajagsgcar
carssfjk
-----------------------------------------output--------------------------------------
xcar
cardf
carssfjk
ghashas car
disduyuucarsdy
gsas sajgsa car
hgafscar hjagdjggds samhgcar
jasghhhhhhhhhhgajgjashjahhagshgajagsgcar

