Basic Linux Commands with a Twist

Basic Linux Commands with a Twist

What are the Linux commands to:

Task 1: View the content of a file and display line numbers.

cat -n filename

Task 2: Change the access permissions of files to make them readable, writable, and executable by the owner only.

chmod 777 filename

Task 3: Check the last 10 commands you have run.

history

Task 4: Remove a directory and all its contents.

rm -r directoryname

Task 5: Create a fruits.txt file, add content (one fruit per line), and display the content.

- Create file

touch fruits.txt

- Add Content

vi fruits.txt

- Display content

cat fruits.txt

Task 6: Add content in devops.txt (one in each line) - Apple, Mango, Banana, Cherry, Kiwi, Orange, Guava. Then, append "Pineapple" to the end of the file.

- Add Content

vi devops.txt

- Append content in file

echo Pineapple >>devops.txt

Task 7: Show the first three fruits from the file in reverse order.

head -n 3 devops.txt | tac

Task 8: Show the bottom three fruits from the file, and then sort them alphabetically.

tail -n 3 devops.txt | sort

Task 9: Create another file Colors.txt, add content (one color per line), and display the content.

cat Colors.txt

Task 10: Add content in Colors.txt (one in each line) - Red, Pink, White, Black, Blue, Orange, Purple, Grey. Then, prepend "Yellow" to the beginning of the file.

echo -e "Red\nPink\nWhite\nBlack\nBlue\nOrange\nPurple\nGrey" > Colors.txt
echo "Yellow" | cat - Colors.txt > temp && mv temp Colors.txt

Task 11: Find and display the lines that are common between fruits.txt and Colors.txt

- Sort the content of the "Colors.txt" and added them to "Colors_sort.txt"

cat Colors.txt | sort >>Colors_sort.txt

- Sort the content of the "fruits.txt" and added them to "fruits_sort.txt"

cat fruits.txt | sort >>fruits_sort.txt

- Find and display common lines in Colors_sort.txt and fruits_sort.txt

comm Colors_sort.txt fruits_sort.txt

- Another way to find and display common lines in Colors_sort.txt and fruits_sort.txt

  • The -1 option suppresses the output of lines unique to the first file (colors.txt).

  • The -2 option suppresses the output of lines unique to the second file (fruits.txt).

  • Combining -12 means that only lines that are common to both files will be displayed.

comm -12 Colors_sort.txt fruits_sort.txt

Task 12: Count the number of lines, words, and characters in both fruits.txt and Colors.txt.

wc Colors.txt fruite.txt

  • First column: Number of lines.

  • Second column: Number of words.

  • Third column: Number of characters.

  • Last column: Filename.