Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append string on grep multiple results in a single command

Tags:

text

grep

format

I want to append a string on the every line from the grep result.

For example, this command will return several lines:

ls -a | grep "filename"

For example:

filename1
filename2
filename3
filename4

How can I append a string test on each return line using a single command? So that I get this output:

test filename1
test filename2
test filename3
test filename4
like image 569
user3922684 Avatar asked Nov 06 '14 16:11

user3922684


People also ask

How do I grep multiple results?

If you want to find exact matches for multiple patterns, pass the -w flag to the grep command. As you can see, the results are different. The first command shows all lines with the strings you used. The second command shows how to grep exact matches for multiple strings.

How do I grep text from multiple files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

How do I use grep to append?

If you wish to append the output at the end of the file, use >> rather than > as the redirection operator. What this actually does is to start cat and grep concurrently. cat will read from q1. txt and try to write it to its standard output, which is connected to the standard input of grep .


2 Answers

You can do this:

ls -a | grep "filename" | perl -ne 'print "test $_"'
like image 54
ErikR Avatar answered Sep 20 '22 18:09

ErikR


An alternative is to use sed (which is specifically a Stream EDitor):

ls -a | grep "filename" | sed 's/^/test /'

or

ls -a *filename* | sed 's/^/test /'

or even

ls -a | sed '/filename/bx;d;:x;s/^/test /'

like image 34
davemyron Avatar answered Sep 18 '22 18:09

davemyron