Reputation: 483
I understand that grep can extract the specific content from a file line by line. Just wondering how can add another column before or after each line as an index. For example:
grep "aaa" text.txt > tmp.txt
In the tmp.txt file, we can see the content as follows,
aaawekjre
qejrteraaa
wrgeaaaere
However, I would like to add a specific index as an extra column. Therefore, the tmp.txt might look like this:
John aaawekjre
John qejrteraaa
John wrgeaaaere
Upvotes: 3
Views: 2047
Reputation: 113834
$ sed -n '/aaa/ s/^/John /p' text.txt
John aaawekjre
John qejrteraaa
John wrgeaaaere
-n
This tells sed not to print anything unless we explicitly ask it to.
/aaa/ s/^/John /p
This selects lines that contain aaa
. For those lines, we do a substitution (s/^/John /
) to put John
at the beginning of the line and we print the line (p
).
In this way, lines that do not contain aaa
are never printed. Thus, there is no need for a separate grep
process.
Upvotes: 6
Reputation: 4112
try this
grep "aaa" text.txt | awk '{print "John " $0}' > tmp.txt
Upvotes: 2
Reputation: 785146
You can use awk:
awk '/aaa/{print "John", $0}' text.txt > tmp.txt
Upvotes: 7