user3873113
user3873113

Reputation: 27

Append string on grep multiple results with variable in a single command

The filename contain space, e.g. example like this.txt and I want to append " on the prefix and postfix of that string. e.g. "example like this.txt".

Moreover, I also want to append the number on every line from the grep result

For example, this command will return several lines:

ls -a | grep "filename"

For example:

example filename a.txt
example filename b.txt
example filename c.txt
example filename d.txt

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

1 "example filename a.txt"
2 "example filename b.txt"
3 "example filename c.txt"
4 "example filename d.txt"

Upvotes: 2

Views: 1967

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85875

If you want a single command you will need to go with something like awk, perl or python:

For example:

$ ls -la | awk '/filename/{printf "%s %s%s%s\n",++i,q,$0,q}' q='"' 
1 "example filename a.txt"
2 "example filename b.txt"
3 "example filename c.txt"
4 "example filename d.txt"

Upvotes: 3

Related Questions