Move a line containg "char" above line containing "xchar"

Okay, so I have a rather large text file and will have to process many more and this will save me hours of work.
I'm not very good at scripting, so bear with me please.

Working on Linux RHEL

I've been able to filter and edit and clean up using sed, but I have a problem with moving lines.

I have a file containing entries like this:

<tr>
<td>Manufacturer</td>
<td>Type</td>
<td>Model</td>
<td>OID</td>
<td>IF-Usage</td>
<td>Environment</td>
<td>CPU/MEM</td>
</tr>
<tr>
<td>[[Cisco]]</td>
<td>.1.3.6.1.4.1.9.1.1249 </td>
TYPE            = Router
VENDOR          = Cisco
MODEL           = 892F
CERTIFICATION   = CERTIFIED
CONT = Cisco-Router-Entity
NEIGHBOR = Cisco-Cdp
HEALTH = Cisco-Router

For each occurence in the file (literally thousands), I need to move the line "TYPE = Router"
Below the line "<td>[[Cisco]]</td>"

After that I'll need to move other variables around and convert everything to html tables, but that I can do already.
Because I will reuse the command for the other variables in the text, it would be better to do it using matching char rather than just counting lines.

Any ideas?

awk '/'<td>[[Cisco]]</td>'/{print;print "TYPE            = Router";next}1' then try removing 'TYPE            = Router' pttern

that would allow me to find each occurrence of the line, but it won't move it where I want.

awk -f rex.awk myFile , where rex.awk is:

BEGIN {
  pat2move="TYPE            = Router"
  patBelow="[[Cisco]]"
}
$0 ~ pat2move {next}
$0 ~ patBelow { $0 = $0 ORS pat2move}
1

Disclaimer: with some basic assumptions - YMMV

1 Like

This gives an error at "="

My crystal ball is being repaired...
Please post exactly what you tried, sample file and the exact error message.

awk -f rex.awk fileA.txt     
awk: rex.awk:2: 2move="TYPE=Router"
awk: rex.awk:2:      ^ syntax error

and what's your rex.awk look like?

Did you change pat2move to 2move
or did you add a space pat 2move ?
--
Here is a more sophisticated solution:

awk '
 BEGIN {
   lineBelow="<td>[[Cisco]]</td>"
   pat2move="TYPE *= *Router"
   scope=8
 }
 ($0==lineBelow) {n=scope; print; next}
 (n==0) {print; sep=""; next}
 ($0~pat2move) {print $0 RS save; n=0; next}
 {save=save sep $0; sep=RS}
 (--n==0) {print save}
 END {if (n>0) print save}
' fileA.txt

The pat2move is a RegularExpression: a * means the previous character is present zero or more times.
E.g the TYPE *= *Router matches

TYPE =Router

and

TYPE     = Router

. You can also put a character class like TYPE[[:space:]]*=[[:space:]]*Router .
scope is the number of following lines to search for the pat2move .
The lineBelow is a string to be compared with the whole line.

I think this is a lot easier in ed than in awk . Try:

ed -s file <<-EOF
	g/^TYPE[[:blank:]]*=[[:blank:]]*Router/.m?<td>[[][[]Cisco[]][]]</td>?
	w
	q
EOF