grep and sed
Find text matching a pattern in log files and command output using the grep command and regular expressions.
Task 1:
Find the rows that contain abcde from file /etc/testfile, and write it to the file /tmp/testfile, and the sequence is requested as the same as /etc/testfile
Solution:
vim /etc/testfile # add some lines which contains abcde
grep 'abcde' /etc/testfile > /tmp/testfile
Task 2:
Download the document from ftp://instructor.example.com/pub/testfile
, find all lines containing abcde
and redirect to /mnt/answer document, then rearrange the order according the original content.
Solution:
wget ftp://instructor.example.com/pub/testfile
grep '[abcde]' /tmp/testfile > /mnt/answer
grep '[abcde]' /tmp/answer
Task 3:
Find all lines in the file /usr/share/mime/packages/freedesktop.org.xml that contain the string ich. Put a copy of these lines in the original order in the file /root/lines. /root/lines should maintain contain no empty lines and all lines must be exact copies of the original lines in /usr/shre/mime/packages/freedesktop.org.xml
Solution:
grep ich /usr/share/mime/package/freedesktop.org.xml > /root/lines
sed -i '/^$/d' /root/lines
cat /root/lines
Task 4:
Find all lines in the file /usr/share/dict/words
that contain the string seismic
. Put a copy of all these lines in their original order in the file /root/wordlist
. /root/wordlist
should contain no empty lines and all lines must be exact copies of the original lines in /usr/share/dict/words
Solution:
grep seismic /usr/share/dict/words > /root/wordlist
sed -i '/^$/d/' /root/wordlist
grep seismic /root/wordlist
Task 5:
Search the string nologin in the /etc/passwd
file and save the output in /root/strings
Solution:
grep nologin /etc/passwd > /root/strings
grep nologin /root/strings
Last updated
Was this helpful?