Inserting n characters to beginning of line if match

I would like to insert n number of characters at the beginning of each line that starts with a given character. If possible, I would be most appreciative for a sed or awk solution.

Given the data below, I would like to be able to insert either 125 spaces or 125 "-" at the beginning of every line that begins with "@".

 
@PS001,001 VWB                 0   2 -1 -1 -1  5 -1   -1 -1  3  2     
@PS001,001 HJ==                0   7 -1 -1 -1 -1 -1   -1  3  1  2
 PS001,001 >CR=                0   2 -1 -1 -1  5 -1   -1 -1  3  2

Thank you so much.

What have you tried so far?

1 Like

I have tried various iterations of the following basic codes:

sed "/^@/s/^/i $(printf '%.0s-' {0..125}/g)" file1.txt
sed '/^@/s/^@/ \{125\}@/g' file1.txt
awk '{if($0 ~/^@/); BEGIN{for(c=0;c<125;c++) printf "-"; printf "\n"}' file1.txt
1 Like

Here are a couple of possible solutions:

echo "inserting 125 spaces..."
awk '{printf("%*s\n", 125 * (substr($0, 1, 1) == "@") + length, $0)}' file
echo "inserting -..."
awk '/^@/{$0 = "-" $0}1' file
1 Like

Thank you so much for this Don. In reviewing your code, I left things a bit ambiguous in my original post. I meant to say either 125 spaces or *125* dashes ("-"). I very much like the elegance of:

awk '/^@/{$0 = "-" $0}1' file

Is there a way that awk can be told to do 125 of the leading "-"? Or is the only solution to substitute "-" for "/s" in:

awk '{printf("%*s\n", 125 * (substr($0, 1, 1) == "@") + length, $0)}' file

Thus:

awk '{printf("%*-n", 125 * (substr($0, 1, 1) == "@") + length, $0)}' file

Sorry for misunderstanding what you were trying to do. Maybe something like:

awk '
BEGIN {	for(i = 1; i <= 125; i++)
		dl = dl "-"
}
{	print (($0 ~ /^@/) ? dl : "") $0
}' file
1 Like

Try also

awk '1+gsub (/^@/, sprintf (" %125s", "@"))' file

and

awk 'BEGIN {T = sprintf ("%125s", " "); gsub (/ /,"-", T)} 1+gsub (/^@/, T "@")' file

or

awk 'BEGIN {while (length(T) < 125) T = T "-" } 1+gsub (/^@/, T "@")' file