To print from the first line until pattern is matched

Hi I want to print the line until pattern is matched.

I am using below code:

sed -n '1,/pattern / p' file

It is working fine for me , but its not working for exact match.

sed -n '1,/^LAC$/ p' file

Input:

LACC	FEGHRA		0
LACC	FACAF		0
LACC	DARA		0
LACC	TALAC		0
LAC 	ILACTC		0
LACC	Kerzner		0
LAAS	TOTAL		0
LACC	LAC		0
LACC	IRSI		0
LACC	Asocianes CTO	0
LACC	Kerzner		0

Expected Output:

LACC	FEGHRA		0
LACC	FACAF		0
LACC	DARA		0
LACC	TALAC		0
LAC 	ILACTC		0

That is because $ would match end of line and not end of string. Depending on the exact nature of the input you could match for space/tab instead, or just not a letter:

sed -n '1,/^LAC[^a-zA-Z]/p' file
1 Like

And if the Input is like below:

LACC	FEGHRA		0
LACC	FACAF		0
LACC	DARA		0
LACC	TALAC		0
LACC 	ILACTC		0
LACC	Kerzner		0
LAAS	TOTAL		0
LACC	LAC		0
LACC	IRSI		0
LACC	Asocianes CTO	0
LACC	Kerzner		0

Then Can I achive the below output:

LACC	FEGHRA		0
LACC	FACAF		0
LACC	DARA		0
LACC	TALAC		0
LACC 	ILACTC		0
LACC	Kerzner		0
LAAS	TOTAL		0
LACC	LAC		0

Thank you

Although this

sed -n '1,/    LAC/p' file

will work with the sample given, try this

sed -rn '1,/^[^         ]+[     ]+LAC[  ]+/p' file

to be on the safe side (within the square brackets, there's a space and a <TAB> char). If your sed doesn't support the -r (or -E) option, replace the + with \+ .

1 Like

Hi,
with gnu sed, we can use begin mark and end mark word:

sed -n '1,/\<LAC\>/p' file

Regards.

sed -n '1,/\<LAC\>/p' file

This doesn't work for me.

Only the below code is working.

sed -n '1,/    LAC/p' file

Ok, then a posix solution:

sed -n '1,/[^[:alnum:]_]LAC[^[:alnum:]_]/p' file

PS: posix definiton of word class is [A-Za-z0-9_]

Regards.

With awk:

awk '{print; if ($1=="LAC") exit}' file 
awk '{print; if ($2=="LAC") exit}' file 
awk '{print; if ($1=="LAC" || $2=="LAC") exit}' file 

But there is one catch in the case of sed. If the match is on the first line, then it will not work.. To handle this case you need a GNU extension (GNU sed):

gsed -n '0,/\<LAC\>/p' file

awk does not have this problem and can also use a range expression and also can have an exact field match as noted by MadeInGermany, so you do not need to delimit the search:

awk 'NR==1, $1=="LAC"||$2=="LAC"' file

or

awk -v s=LAC 'NR==1, $1==s||$2==s' file

MadeinGermany's approach with the exit statement would be more efficient.

--
This exit approach would also work with regular sed and this does not have the match-on-line-1 catch:

sed '/^LAC$/q; /^LAC[[:blank:]]/q; /[[:blank:]]LAC[[:blank:]]/q' file