简体   繁体   中英

In Bash, grep for a line and print that line in a file but with more information

In bash, I am using the grep command to print the result to a file:

  grep "4 CA   1" CVOLOPTs*SYMREMO.out | grep "11 O    0 0 0" >> data.dat

Which prints the following in the data.dat file:

 4 CA   1     2.3311     4.4052   11 O    0 0 0

I would like to make the data.dat look like the following:

 252   4 CA   1     2.3311     4.4052   11 O    0 0 0

I have tried something like:

grep "4 CA   1" CVOLOPTs*SYMREMO.out | grep "11 O    0 0 0" >> echo "252" data.dat

But does not work.

I would appreciate if you could help me please.

An additional pipe with awk could do the trick:

grep "4 CA   1" CVOLOPTs*SYMREMO.out | grep "11 O    0 0 0" | awk ´{print "252",$0}´ >> data.dat

the whole thing can be done with a single awk :

awk ´/4 CA   1/ && /11 O    0 0 0/ {print "252",$0}' CVOLOPTs*SYMREMO.out >> data.dat

$0 is the entire current line. In this situation, the line selected by the 2 regex.

awk reads each line one by one.

Regex stands for regular expression. With awk they are enclosed into / : eg /4 CA 1/

/4 CA 1/ && /11 O 0 0 0/ is an expression: it is true when the line being read matches both the first regex and ( && ) the second regex. In this situation there are just strings; see 9. Regular Expressions from the Open Group Base Specifications Issue 6.

You may not need to use grep as you could achieve the desired output with this awk one-liner :

awk '/4 CA   1/ && /11 O    0 0 0/{printf "252\t%s\n",$0}' CVOLOPTs*SYMREMO.out >> data.dat

I have put a tab after 252 which might change to one or more whitespaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM