Home > Software engineering >  Bash printing lines if line before matches
Bash printing lines if line before matches

Time:07-29

I only need to print the line directly before the - or -- symbol in bash which contains the location of the change. how can I edit this text to do so?

Input:

--- /opt/   
 /opt/location1:
 /opt/location2:
 /opt/location3:
 -rw-r--r-- 1 ra 
--rwxr-xr-x 1 rt 
 -rwxr-xr-x 1 ft 
 /opt/location4:
 /opt/location5:
 -rw-r--r-- 1 dra 
--rwxr-xr-x 1 drt 
 -rwxr-xr-x 1 dft 

output

  /opt/location3:
 -rw-r--r-- 1 ra 
--rwxr-xr-x 1 rt 
 -rwxr-xr-x 1 ft 
 /opt/location5:
 -rw-r--r-- 1 dra 
--rwxr-xr-x 1 drt 
 -rwxr-xr-x 1 dft

CodePudding user response:

You can probably just do grep -B1 '^[ -]-' input, but the output is not quite what you want. To get the exact output you demonstrate, try:

awk '/^[ -]-/ && NR > 1{if(p) print prev; p=0; print; next} { p=1; prev = $0}' input
  •  Tags:  
  • bash
  • Related