How to delete the previous line after pattern match?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How to delete the previous line after pattern match?
# 1  
Old 11-17-2016
How to delete the previous line after pattern match?

Team,

I am writing a shell script to perform few health checks of the system, where I need to delete the previous line in the text file after pattern match using sed (or) awk.

Could you please help me out on this?

For example,
Code:
<td>
<td style=color:green align=center>
</td>
</tr>
</table>

I want the pattern to be matched as "<td style=" but only the previous line "<td>" to be removed. So, the output should look like follows:
Code:
<td style=color:green align=center>
</td>
</tr>
</table>

This is on AIX.

Moderator's Comments:
Mod Comment please use code tags next time thanks

Last edited by vbe; 11-17-2016 at 09:46 AM.. Reason: please use code tags next time thanks
# 2  
Old 11-17-2016
Hello Nagaraj R,

Welcome to forums, please use code tags for commands/codes/Inputs which you are using into your posts as per forum rules. Could you please try following and let me know if this helps you.
Code:
awk '{if($0 ~ /<td style/){Q=$0;} else {if(Q){print Q}};Q=$0}'   Input_file

If you may have any empty lines into your Input_file then following may help you in same.
Code:
awk '{if($0 ~ /<td style/){Q=$0;} else {if(NR>1){print Q}};Q=$0}'  Input_file

Output will be as follows.
Code:
<td style=color:green align=center>
</td>
</tr>

Thanks,
R. Singh
This User Gave Thanks to RavinderSingh13 For This Post:
# 3  
Old 11-17-2016
Try also
Code:
sed '/<td>/ {N;s/^<td>\n\(<td style=\)/\1/}' file

This User Gave Thanks to RudiC For This Post:
# 4  
Old 11-17-2016
A Unix sed needs a newline or a semicolon before the closing }
Code:
sed '/<td>/ {$!N;s/^<td>\n\(<td style=\)/\1/;}' file

Also most Unix sed have the bug to not do the default print if there is a N command on the last input line, therefore the usual workaround.
This User Gave Thanks to MadeInGermany For This Post:
# 5  
Old 11-17-2016
MadeInGermany's answer in sed is worthy of study.
Code:
 If we found <td> first check to see if this is not the last line "$!", append
 the next line "N" into the pattern space which now contains two lines separated
 by newline "\n".  The \(through\) identifies a pattern (here the word "through")
 to be played back with \1.  The "s" command finds <td> on one line and
 <td style= on the next and replaces it with just <td style=, deleting the first line
 and keeping the next one intact.

This User Gave Thanks to wbport For This Post:
# 6  
Old 11-18-2016
Thank you Rudic and MadeInGermany. It worked and helped me to get this task done.

Thank you others as well for the response.!!
# 7  
Old 11-18-2016
Hi.

The command ed may be easier for some folks to understand:
Code:
#!/usr/bin/env bash

# @(#) s1       Demonstrate find match, delete previous line, ed.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
em() { pe "$*" >&2 ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C ed pass-fail

original=${1-original}
FILE=data1
rm -f $FILE
cp $original $FILE
E=expected-output.txt

pl " Input data file $FILE:"
cat $FILE

pl " Expected output:"
cat $E

# Find match, current line number is in symbol "."
# The previous line is ".-1", so delete that line.
pl " Results, from ed:"
ed $FILE <<EOF
/<td style=/
.-1d
w
q
EOF

pl " Results, content of edited file:"
tee f1 < $FILE 

pl " Verify results if possible:"
C=$HOME/bin/pass-fail
[ -f $C ] && $C || ( pe; pe " Results cannot be verified." ) >&2

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
aix 7.1.0.0
bash GNU bash 4.2.10
ed - ( /usr/bin/ed, Sep 5 2012 )
pass-fail - ( local: RepRev 1.8, ~/bin/pass-fail, Nov 18 17:57 )

-----
 Input data file data1:
<td>
<td style=color:green align=center>
</td>
</tr>
</table>

-----
 Expected output:
<td style=color:green align=center>
</td>
</tr>
</table>

-----
 Results, from ed:
62
<td style=color:green align=center>
57

-----
 Results, content of edited file:
<td style=color:green align=center>
</td>
</tr>
</table>

-----
 Verify results if possible:

-----
 Comparison of        4 created lines with        4 lines of desired results:
 Succeeded -- files (computed) f1 and (standard) expected-output.txt have same content.

Best wishes ... cheers, drl
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. AIX

Print nth previous line after match

Please help me print nth line after match awk or sed one line command. (3 Replies)
Discussion started by: sushma123
3 Replies

2. Shell Programming and Scripting

awk to combine lines from line with pattern match to a line that ends in a pattern

I am trying to combine lines with these conditions: 1. First line starts with text of "libname VALUE db2 datasrc" where VALUE can be any text. 2. If condition1 is met then continue to combine lines through a line that ends with a semicolon. 3. Ignore case when matching patterns and remove any... (5 Replies)
Discussion started by: Wes Kem
5 Replies

3. Shell Programming and Scripting

How to print previous line of multiple pattern matched line?

Hello, I have below format log file, Comparing csv_converted_files/2201/9747.1012H67126.5077292103609547345.csv and csv_converted_files/22019/97447.1012H67126.5077292103609547345.csv Comparing csv_converted_files/2559/9447.1012H67126.5077292103609547345.csv and... (6 Replies)
Discussion started by: arvindshukla81
6 Replies

4. Shell Programming and Scripting

Delete line by pattern match in column

file: 1|12322|tow| 5|23422|pow| 6|23423|cow| 3|34324|how| deletelines: 12322 23423 My command to delete line while read NUM do awk -F"\|" '$2 !~ /`"$NUM"`/' file >file.back mv file.back file done<deletelines (3 Replies)
Discussion started by: Roozo
3 Replies

5. Shell Programming and Scripting

Rearrange or replace only the second line after pattern match or pattern match

Im using the command below , but thats not the output that i want. it only prints the odd and even numbers. awk '{if(NR%2){print $0 > "1"}else{print $0 > "2"}}' Im hoping for something like this file1: Text hi this is just a test text1 text2 text3 text4 text5 text6 Text hi... (2 Replies)
Discussion started by: invinzin21
2 Replies

6. UNIX for Advanced & Expert Users

How to find a string in a line in UNIX file and delete that line and previous 3 lines ?

Hi , i have a file with data as below.This is same file. But actual file contains to many rows. i want to search for a string "Field 039 00" and delete that line and previous 3 lines in that file.. Can some body suggested me how can i do using either sed or awk command ? Field 004... (7 Replies)
Discussion started by: vadlamudy
7 Replies

7. Shell Programming and Scripting

Delete line with match and previous line quoting/escaping problem

Hi folks, I've list of LDAP records in this format: cat cmmac.export.tmp2 dn: deviceId=0a92746a54tbmd34b05758900131136a506,ou=devices,ou=customer,ou=nl,o=upc cmmac: 00:13:11:36:a5:06 dn: deviceId=0a92746a62pbms4662299650015961cfa23,ou=devices,ou=customer,ou=nl,o=upc cmmac:... (4 Replies)
Discussion started by: tomas.polak
4 Replies

8. Shell Programming and Scripting

Find pattern a delete previous 5 lines

Hi guys, i have the follow problem i need to delete 10 row before the pattern and 1 after and the pattern row itself. file looks like: frect 9.8438 25.8681 10.625 25 . dynprop \ (# \ (call fox_execute(__self))) \ (FOX_VAR_29 \ ... (4 Replies)
Discussion started by: EjjE
4 Replies

9. UNIX for Dummies Questions & Answers

return previous line for pattern match

Hi, Need some idea on file processing, I have file like below, Processing al sources ... ...No value found : CHECK. Completed comparing all sources. Comparing schedulers... Processing al targets ... ...No value found : From above I need to extract the line where "No value... (4 Replies)
Discussion started by: braindrain
4 Replies

10. Shell Programming and Scripting

delete a line that does not match the pattern

hi, i am parsing a file, in that searching for lines those contains "$threadNo.Received message:" , if that line contains the required fields write them into a separate file other wise ignore them. i am using the following code,but it is printing all the lines , i dont want to rpint , please help... (3 Replies)
Discussion started by: Satyak
3 Replies
Login or Register to Ask a Question