'Using AWK to skip first line and pattern match for the rest
In the following text, I would like to skip the first line and put $ in front of lines starting with Part1. I have included my script, but it not working. Can you please help?
Input
------
Intro
Part1 Yellow
Part2 Red
Part3 Green
Part1 Yellow
Desired output:
--------------
$Part1 Yellow
Part2 Red
Part3 Green
$Part1 Yellow
Code:
awk 'NR>1 {$0~/Part1/($0="$ "$0)}1' myfile
Error:
awk: Syntax error Context is:
>>> NR>1 {$0~/Part1/( <<<
Solution 1:[1]
With your shown samples please try following awk. Simple explanation would be, its skipping 1st line(FNR>1) condition AND its checking if a line starts with Part1 then its adding $ in front of current line's value. Then mentioning 1 will print the edited/non-edited line.
awk 'FNR>1 && /^Part1/{$0="$"$0} 1' Input_file
Solution 2:[2]
If you want to skip the first line and not to print it, I'd make this change in your code:
awk 'NR>1 {if ($0 ~ /^Part1/) $0="$"$0;print}' file
or more concise:
awk 'NR > 1 {if (/^Part1/) $0="$"$0;print}' file
$Part1 Yellow
Part2 Red
Part3 Green
$Part1 Yellow
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Carlos Pascual |
