Linux get string from file

5 Commands to View the Content of a File in Linux Command Line

If you are new to Linux and you are confined to a terminal, you might wonder how to view a file in the command line.

Reading a file in Linux terminal is not the same as opening file in Notepad. Since you are in the command line mode, you should use commands to read file in Linux.

Don’t worry. It’s not at all complicated to display a file in Linux. It’s easy as well essential that you learn how to read files in the line.

Here are five commands that let you view the content of a file in Linux terminal.

5 commands to view files in Linux

Before you how to view a file in Unix like systems, let me clarify that when I am referring to text files here. There are different tools and commands if you want to read binary files.

1. Cat

This is the simplest and perhaps the most popular command to view a file in Linux.

Cat simply prints the content of the file to standard display i.e. your screen. It cannot be simpler than this, can it?

cat displays the content of the file on the screen

Cat becomes a powerful command when used with its options. I recommend reading this detailed tutorial on using cat command.

The problem with cat command is that it displays the text on the screen. Imagine if you use cat command with a file that has 2000 lines. Your entire screen will be flooded with the 200 lines and that’s not the ideal situation.

So, what do you do in such a case? Use less command in Linux (explained later).

The nl command is almost like the cat command. The only difference is that it prepends line numbers while displaying the text in the terminal.

nl command displays text with line numbers

There are a few options with nl command that allows you to control the numbering. You can check its man page for more details.

3. Less

Less command views the file one page at a time. The best thing is that you exit less (by pressing q), there are no lines displayed on the screen. Your terminal remains clean and pristine.

I strongly recommend learning a few options of the Less command so that you can use it more effectively.

There is also more command which was used in olden days but less command has more friendly features. This is why you might come across the humorous term ‘less is more’.

Читайте также:  Free windows phone apps downloads

4. Head

Head command is another way of viewing text file but with a slight difference. The head command displays the first 10 lines of a text file by default.

You can change this behavior by using options with head command but the fundamental principle remains the same: head command starts operating from the head (beginning) of the file.

5. Tail

Tail command in Linux is similar and yet opposite to the head command. While head command displays file from the beginning, the tail command displays file from the end.

By default, tail command displays the last 10 lines of a file.

Head and Tail commands can be combined to display selected lines from a file. You can also use tail command to see the changes made to a file in real time.

Bonus: Strings command

Okay! I promised to show only the commands for viewing text file. And this one deals with both text and binary files.

Strings command displays the readable text from a binary file.

No, it doesn’t convert binary files into text files. If the binary file consists of actual readable text, strings command displays those text on your screen. You can use the file command to find the type of a file in Linux.

Conclusion

Some Linux users use Vim to view the text file but I think that’s overkill. My favorite command to open a file in Linux is the less command. It leaves the screen clear and has several options that makes viewing text file a lot easier.

Since you now know ways to view files, maybe you would be interested in knowing how to edit text files in Linux. Cut and Paste are two such commands that you can use for editing text in Linux terminal. You may also read about creating files in Linux command line.

Источник

Finding a File Containing a Particular Text String In Linux Server

Tutorial details
Difficulty level Easy
Root privileges No
Requirements grep
Est. reading time Less than 2 minutes

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

grep command syntax for finding a file containing a particular text string

The syntax is:
grep » text string to search » directory-path
grep [option] » text string to search » directory-path
grep -r » text string to search «directory-path
grep -r -H » text string to search » directory-path
egrep -R » word-1|word-2 » /path/to/directory
egrep -w -R » word-1|word-2 » directory-path
Let us see some common example on how to use grep to search for strings in files.

How to search and find all files for a given text string

In this example, search for a string called ‘redeem reward’ in all text (*.txt) files located in /home/tom/ directory, use:
$ grep «redeem reward» /home/tom/*.txt
OR
$ grep «redeem reward»

Task: Search all subdirectories recursively

You can search for a text string all files under each directory, recursively with -r option:
$ grep -r «redeem reward» /home/tom/
OR
$ grep -R «redeem reward» /home/tom/
Look for all files containing cacheRoot text on Linux:
grep -R cacheRoot /home/vivek/

Trying to find all files containing specific text on my Linux desktop

Task: Only display filenames

By default, the grep command prints the matching lines. You can pass -H option to print the filename for each match:
$ grep -H -r «redeem reward» /home/tom
Sample outputs:

To just display the filename use the cut command as follows:
$ grep -H -R vivek /etc/* | cut -d: -f1
Sample outputs:

Task: Suppress file names

The grep command shows output on a separate line, and it is preceded by the name of the file in which it was found in the case of multiple files. You can pass the -h option to suppress inclusion of the file names in the output:
$ grep -h -R ‘main()’

Task: Display only words

You can select only those lines containing matches that form whole words using the -w option. In this example, search for word ‘getMyData()’ only in

/projects/ dirctory:
$ grep -w -R ‘getMyData()’

Task: Search for two or more words

Use the egrep command as follows:
$ egrep -w -R ‘word1|word2’

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Task: Hide warning spam

grep command generate error message as follows due to permission and other issues:

No such file or directory
No such device or address
Permission denied

To hide all errors or warning message spam generated by the grep command, append 2>/dev/null to grep command. This will send and hide unwanted output to /dev/null device:
$ grep -w -R ‘getMyData()’

Task: Display matched text in color

Pass the —color option to the grep command display matched text/words in color on the terminal:

Fig.01: grep command in action with colors and hiding the warnings on screen

Task: Ignore case

Our final example ignore case distinctions in both the search PATTERN and the input files:
grep -i -R ‘word’ /path/to/dir
grep -i -r ‘income tax’

How do I find all files containing specific text on Linux?

The syntax is:
egrep ‘pattern’ -rnw /path/to/dir/
egrep ‘word1|word2’ -rnw /home/vivek/backups/

Finding text strings within files using grep

In this example search for lines starting with any lowercase or uppercase letter:
grep «^[a-zA-Z]» -rns

  • -r – Recursive search
  • -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option
  • -n – Display line number of each matched line
  • -s – Suppress error messages about nonexistent or unreadable files
  • -w – Only work on words i.e. search only those lines containing matches that form whole words
  • -l – Show the name of each input file when match found
  • -i – Ignore case while searching

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to append string/data to a file in Linux

This article will show you how to append a string (or any data) to the end of a file under Linux/Unix. Appending is done very simply by using the append redirect operator >>. Simply use the operator in the format data_to_append >> filename and you’re done. Below are several examples:

Examples to Append Data to a File

  1. To append the string “hello” to file greetings.txt
    echo «hello» >> greetings.txt
  2. To append the contents of the file temp.txt to file data.txt
    cat temp.txt >> data.txt
  3. To append the current date/time timestamp to the file dates.txt
    date >> dates.txt

Take it one step further – Find out how to insert a string to the beginning of a file

realy helpful, thanks!

Thank you, it helped me a lot.

how can add the data to the file without open the file in UNIX/Linux ?

Great article!
Thanks

Thanks, ’twas helpful !!

Thanks a lot.. really helped.:)

Thanks for the comments. Are there any other examples that you think should be added to this article? Anything else you all are looking for?

this was really helpful…

I am having two text file (Let’s assume sample1.txt & sample2.txt). sample1.txt contains only one line “xyz” while sample2.txt contains many lines like
“abc
def
ghi
jkl
mno”

Now I need to create a new file which should contain the contents of both the file like below

“xyz abc
xyz def
xyz ghi
xyz jkl
xyz mno”

Is there any way in Unix to achieve the same ?

Any type of help will be much appreciated.

Was very helpful.
Thanks a lot..

I thank you for your brevity.

How to edit the contents in unix through command

Sir, Your giving append example really helpfull for me. Thax alot

Thank you very much! I was looking for how to set a new line in a txt file, and just add one echo per line in the loop resolve it. Thank you!

Thank you so much! I have been looking for this all the morning!

In response to Prashant:
—————————–
user@host0

]$ for x in `cat sample2.txt`
> do
> echo “`cat sample1.txt` $x” >> sample3.txt
> done
user@host0

]$ cat sample3.txt
xyz abc
xyz def
xyz ghi
xyz jkl
xyz mno

Thanx man. Really helpful tip.

Really halpful . thanks lot..

Hello! Quick question that’s totally off topic. Do you know
how to make your site mobile friendly? My blog looks weird when browsing from my iphone4.
I’m trying to find a theme or plugin that might
be able to resolve this issue. If you have any recommendations, please share.
Cheers!

Thanks a ton. It was really helpful.

I got one question: If i have same file test.txt in multiple directories, like dir1, dir2, dir3 how can I add a string using single command.
i have tried below command (i know i’m stupid)
echo “test” >> dir*/test.txt
and got below error:
-bash: /home/blnc/file*/test.txt: ambiguous redirect

Your help is greatly appreciated in advance

Use this to find all the files called test.txt under the current tree and to append a line:

for f in `find . -name test.txt`; do echo “test” >> $f; done;

I am looking to append a string to a particular string as a reference in sample.txt or sample.xml, Can Someone shed some light on it

to
appended sample.xml with “valid” as reference string

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Читайте также:  Dvd rom не видит диски windows
Оцените статью