Ubuntu Forums Archive Viewer

[Howto/Reference] Finding strings in files using the Command Line

Archived thread 1062890 from Outdated Tutorials & Tips. Markdown source: Outdated_Tutorials_&_Tips/thread_1062890_[HowtoReference]_Finding_strings_in_files_using_th.md

Original URL About this archive
#1

Okay, I decided to write a tutorial on how to find strings in files in the command line. This can be handy if your xorg.conf is broken on an OS that does not have a nice 'xfix' feature (alright, so you can run X -configure, but not everyone knows that).

The first thing I want to do is kill a method that has been spreading like wildfire (I myself helped spread it until someone showed me the right way to do it). Many people will tell you to do this to find a string in a file:


$ cat xorg.conf | grep Device

$ cat -n xorg.conf | grep Device

$ grep -n Device xorg.conf

grep can also search through multiple files with one command:


$ grep -n Device xorg.conf xorg.conf.old xorg.conf.200811071232

You can also reverse grep's functionality by using the -v flag. So instead of printing lines that have a certain string, it will print all lines that DON'T have that string.


$ grep -n -v Device xorg.conf

$ grep -n -i device xorg.conf

$ grep -n Device "Card0" xorg.conf

$ grep -n "Device \"Card0\"" xorg.conf

$ grep -n -e "Device \+\"Card0\"" xorg.conf

Now, how about find and replace? Well, you could use nano's ^W ^R function, or you could use sed to automagically do it for you, without opening an editor!


$ sed -i s/Card0/nVidia GeForce 8800GT/ xorg.conf

Regex can be used in most sed versions without having to add the -r flag, but some require it, so in scripts and other portable things (such as tutorials) use the -r flag for regex


$ sed -i -r s/Card\./nVidia GeForce 8800GT/ xorg.conf

Also note: In general, you can put two single dash flags together into one, like so:


$ sed -ir s/Card0/nVidia GeForce 8800GT/ xorg.conf

I kept them apart to make it easier to see what i had changed.

I hope this helps someone! If you have any questions or catch any errors please let me know!