Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Join line containing pattern to preceding line 1

Status
Not open for further replies.

stu78

Programmer
May 29, 2002
121
0
0
GB
Hi,

I have a large file containing lots of data, however, I want to do the following;

Find any lines containing the pattern cn=

and join this line to the preceeding line (same as shift J in vi)- if that makes sense?


 
A starting point:
awk 'NR>1 && !/cn=/{printf "\n"}{printf "%s",$0}END{printf "\n"}' /path/to/input >output

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 

Minor fix: add a space before the %s:
Code:
#--- Here ---V
#...{printf " %s"...


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
In fact, if you want a space only before the joined line:
awk 'NR>1{printf ($0~/cn=/?" ":"\n")}{printf "%s",$0}END{printf "\n"}' /path/to/input >output

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi PHV,

Thanks for this, and it works great.

However, now I need to put this into a perl script & I am having issues with getting it to work. I have tried backticks, qq etc. and no good. Any ideas how to make this work within a perl script?

I run this ->

my $tmpfile_2 = qq|/tmp/somefile2.bak|;
my $awk_cn_command = qq|awk 'NR>1 && !/cn=/{printf '"\n"'}{printf '"%s"',$0}END{printf '"\n"'}' $logout > tmpfile_2|;
print $awk_cn_command;
qx|$awk_cn_command|;

and the output I get is;

awk 'NR>1 && !/cn=/{printf '"
"'}{printf '"%s"',./login_errors.pl}END{printf '"
"'}' /tmp/failure.log > tmpfile_2awk: syntax error near line 2
awk: illegal statement near line 2

so the /n is breaking it for some reason...
 
Figured out the issue; needed to be;

my $awk_cn_command = qq|awk 'NR>1 && !/cn=/{printf "\\n"}{printf "%s",\$0}END{printf "\\n"}' $tmpfile_1 > $tmpfile_2|;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top