In: Computer Science
I am attempting to write a script using bash on Linux. My program must save the long list format of the parent directory to a text file. Then, it must print how many items are in this parent directory. Then, it must sort the file in reverse order and save it to a different text file.
I understand that the parent directory is accessed using cd .., and I understand that a file can be written to by echoing and using >> fileName, and that |wc -l can be used to count the lines, but I am otherwise lost.
Any help would be greatly appreciated, thank you.
Unix/Linux programs are like Lego blocks. They do one thing, and they do it well. Using these blocks we can build a desired script. So lets see, what kind of programs / Lego blocks we have.
ls -l
Long list files and folders in the current working directory.
ls -l ..
Long list files and folders in the parent directory of the current working directory.
ls -l .. > filelist,txt
Save the long list files and folders in the parent directory to filelist.txt.
ls -1
List files in current directory (one per line) (output to standard output ./ terminal ).
ls -1 | wc -l
Pipe the output of one program ( ls -1 ) to another program ( wc -l ), this will count the number of lines in the output from previous program (list of files in current working directory) and thus we will get the number of files in current working directory. The program on the left executes first, then second and so on.
ls -1 .. | wc -l
Count the number of items in the parent directory.
sort names.txt
Sorts a file names.txt and displays on terminal.
sort -r names.txt
Reverse sorts a file names.txt and displays on terminal.
sort -r filelist.txt > sorted_filelist.txt
Reverse sorts the filelist that we created earlier and save it as a new file sorted filelist.txt
Putting together all the above examples we write the following script:
#!/bin/bash
ls -l .. > filelist.txt
ls -1 .. | wc -l
sort filelist.txt > sorted_filelist.txt
Once you run this script, you'll see the count of items on your screen and two files 'filelist.txt' and 'sorted_filelist.txt' will appear in the current working directory.
Feel free the comment any queries regarding this solution or
somehow if it doesn't work for you. :)