In: Computer Science
Unix command lines.
A) Assume that your current working directory is NOT the same as your home directory. Print all file and subdirectory names of your home directory into a file named file2.
B) Copy the text from line 11 to line 20 of a given file input.txt and append the copied text at the end of the file output.txt. (Assume that the file input.txt contains more than 20 lines of text contents)
C) Count and display the total number of words in ALL files in the current working directory whose name end with “.txt”
D) Count the number of lines where the word “foo” appears in a given file bar.txt
A. Command : ls -l > files.txt and find . -ls > file2.txt
Explanation : ls command is used to list all the files in the directory. -l option provides one to give all the information. > is used as redirection operator all the output generated previously is stored in the given files.txt.
B. Command : sed -n -e '11,20p' input.txt >> output.txt
Explanation : Sed is a powerful text stream editor. One can do insertion, deletion, search it also support regular expressions. Using -n -e option one can able to copy the specified lines of the provided input file. >> is used for concatenation of the files input. The results are copied at the end of the output.txt file.
C.Command : find *.txt -type f -exec wc -w {} \; | awk '{total += $1} END{print total}'
Explanation : Find command is used to search the files based on the command one provides. Here we have provided *.txt which says that to find all the .txt files in the current directory. With that using wc -w we will compute the wordcount and store them in the buffer array. Pipe command (|) is used to connect two or more commands where the current command output acts as the input to the next command. Awk is line-oriented command which is used to execute the things without the intervention of complex functions. It is famously used for writing effective programs in the form of statements. $1 says that the word-1 of the particular there the number of words in a file is calculated. The aggregation is calculated using awk and then prints the total number of words in ALL the .txt ( text ) files.
D.Command : grep "foo" bar.txt | wc -l
Explanation : Grep is the unix command used to fiter the search using certain pattern. Here “foo” is our pattern to be searched in bar.txt file. As we already discussed pipe command (|) is used to connect two or more commands where the current command output acts as the input to the next command. using wc one can determine the word count -l is the option with which number of lines found out.