I am working in a bash shell and I am trying to print only the line of the first occurrence of the string. For example, for the string 'auir
', if I have the file myfile.txt and it contains:
123
asdf
4wirajw
forauir somethingelse
starcraft
mylifeforauir
auir
something else
tf.rzauir
I want to output "forauir somethingelse
"
So far, I use the command
sed -n '/auir/p' myfile.txt
which gives me all the occurrences of this string. How can I only get the first line that 'auir
' occurs on? It'd be great if it was just a single command or pipeline of commands.
Any insight is greatly appreciated.
With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.
Getting the first character To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.
grep is a program that searches for regular expressions. The first argument for grep is the pattern to look for. In scripts and functions $1 is a reference to the first argument passed to that script or function.
The egrep command belongs to the family of the grep command which is used for pattern searching in Linux. If you have used the grep command, egrep works the same as grep -E (grep Extended regex’) does. Egrep scans a specific file, line to line, and prints the line (s) that contain the search string/regular expression.
This can be done using the -l (lowercase L) flag with the egrep command. Here I am searching for the string “sample” in all the .txt files in the current directory: The search results only print the name of the files that contain the specified string.
I need only grep command. By default grep prints the lines matching a pattern, so if the pattern appears one or more times into a line, grep will print that whole line. Adding the flag -m 7 will tell grep to print only the first 7 lines where the pattern appears.
Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is $sed '3 s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource.
Use this:
grep -m1 auir myfile.txt
This sed
command
sed -n '/auir/p' myfile.txt | head -1
solves your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With