Friday 4 May 2012

UNIX ASSIGNMENT 1


http://ebfa7577.linkbucks.com

Question1:
Write a command to list all the files inside a folder i.e. if there is a folder inside a folder then it should list all files inside the sub-folder which is inside the folder to be listed.
Answer: ls -aR
Ls =list information about files.
-a –all (hidden files also), -R –recursive (list subdirectories)

Question 2:
Search all the files which contains a particular string, say “include” within a folder.
Answer: grep include ./*
Grep = searches the named input file for lines containing a match to the given pattern.
./* = In current directory (.), all files(*)

Question 3:
Rename all the files within a folder with suffix “Unix_” i.e. suppose a folder has two files a.txt and b.pdf than they both should be renamed from a single command to Unix_a.txt and Unix_b.pdf
Answer: for i in *.*;do mv “$i” Unix_”$i”;done;
Loop:
Syntax for variable in no of times;
Do command;
….;
Done;
Here: i= *.* (for all files)
$= to read value of variable.
do mv “$i” Unix_”$i” = rename *.* as Unix_*.*

Question 4:
Rename all files within a folder with the first word of their content(remember all the files should be text files. For example if a.txt contains “Unix is an OS” in its first line then a.txt should be renamed to Unix.txt
Answer: for i in *.txt; do head -1 “$i” > ad.txt ; x=”$(cut -d ‘ ‘ -f1 ad.txt)”; mv “$i” “$x.txt”; done;
Here:
i = *.txt (all text files);
do head -1 “$i” > ad.txt; = prints first line and store in ad.txt file.
x=”$(cut -d ‘ ‘ -f1 ad.txt)” ; = removes first column (field) delimited by space from ad.txt file stores in x.
mv “$i” “$x.txt”; = rename *.txt as value of x .txt.


Question 5:
Suppose you have a C project in a folder called “project”, it contains .c and .h files, it also contains some other .txt files and .pdf files. Write a Linux command that will count the number of lines of your text files. That means total line count of every file. (remember you have to count the lines in .txt files only)
Answer: wc –l *.txt
Explanation :
Here: wc =word count
-l =to count lines
*.txt =all text files

Question 6 :
Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’ within a given folder.
Answer: for i in ./*foo*;do mv “$i” “${i/foo/bar}”;done

Question 7:
Show the most commonly used commands from “history”. [hint: remember the history command, use cut, and sort it.
Answer:history|sort|cut -d ‘ ‘ -f1

No comments: