0

I'm trying to export a css rule from a css file with awk but I am not able to do it. I need only the rules containing the "background-image" line.

#rule{
...
background-image: url(path);
}

Here's what I have tried so far:

awk '/^[#].*{.*background-image.*/','/}/' css/file.css

What am I doing wrong?

At this moment I got the best result using:

/^[#A-Za-z.]/ { accum = 1; }
accum == 1 { css = css $0 "\n"; }
accum == 1 && /background-image/ { found = 1; }
/\}/ { accum = 0; if (found == 1) print css; found = 0; css = ""; }

and it allows me to get a full block with all the selectors

10
  • What is your expected output? Commented Feb 16, 2015 at 14:15
  • Do you mean "export CSS rule"? Commented Feb 16, 2015 at 14:16
  • yes "export". I have many #rules (also .rules), I want to export only the ones containing "background-image: ... " Commented Feb 16, 2015 at 14:18
  • It has been a long time (two decades... ) but I seem to recall that awk matches just one line at a time. But it appears that you can do multi-line matches with contemporary awk implementations: stackoverflow.com/a/12390518/67392 Commented Feb 16, 2015 at 14:24
  • mmm so awk is not capable Commented Feb 16, 2015 at 14:48

1 Answer 1

1

Turn accumulation on after matching an open brace. Accumulate all lines while flag is on. Turn off after closing brace is seen. Print only if background-image found during accumulation. If you want to include lines before the match you do do something like this.

{ line4 = line3; line3 = line2; line2 = line1; line1 = $0 "\n"; }
/\{/ { accum = 1; head = line4 line3 line2 line1; }
accum == 1 { css = css $0 "\n"; }
accum == 1 && /background-image/ { found = 1; }
/\}/ {
    accum = 0;
    if (found == 1) print head css;
    found = 0; css = "";
}

You had said in comments "I need the full block from # (or . ) to }" but I'm getting the impression that you really just want this.

/\{/ { selector = $0 }
/background-image/ { print selector "\n" $0 "\n}\n" }
Sign up to request clarification or add additional context in comments.

19 Comments

What is this syntax about?
It's like a C program. A generic awk script has patterns (often a regular expression) and actions (inside braces). You probably want to put this in it's own file and refer to it from the command line.
I have a syntax error near } in the first line. I m doing awk [that stuff] file.cs
Try putting the script in a file, like say cssbckimg.awk, and use awk -f cssbckimg.awk mycss.css from the command line.
same issue, syntax error in the second line near \n
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.