robusta
robusta

Reputation: 229

Move last character of line to specific column -- sed? awk?

I need to replace all lines ending with specific character (say, &) such that this character should be in certain column (say, 80). Which tool is best? I have started thinking about sed:

sed 's/\(.*\)&/\1 <what should be here??> &/'

but cannot understand how to replace with variable number of spaces such that & goes to column 80. Thanks!

Upvotes: 2

Views: 406

Answers (4)

Ed Morton
Ed Morton

Reputation: 203159

awk '/&$/{$80="&"}1' file

Upvotes: 0

David W.
David W.

Reputation: 107040

Awk and Perl will both work. Both have printf and substr:

#! /usr/bin/env perl
use warnings;
use strict;

my $string = "this is some text &";

my $last_char = substr($string, -1, 1);
$string =  substr ($string, 0, length ($string ) - 1);
printf qq(%-79.79s%s\n), $string, $last_char;

The substr command is available in both Awk and Perl.

The whole command could be made into a one liner:

printf qq(%-79.79s%s\n), substr ($string, 0, length ($string ) - 1), substr($string, -1, 1);

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77075

Not sure if I understand your question correctly but you can try something like (assuming your file is space delimited):

awk '/&$/ {for(i=1;i<=NF;i++) $i=(i==80)?"& "$i:$i}1' yourFile

Upvotes: 1

Greg Bacon
Greg Bacon

Reputation: 139421

Use the /e switch to s/// that tells Perl to evaluate the replacement portion to compute the result.

#! /usr/bin/env perl

use strict;
use warnings;

while (<>) {
  s/^(.*)(&)$/$1 . " " x (79 - length $1) . $2/e;
  print;
}

Sample run:

$ echo -e 'foo&\n&\nbar     &\nbaz' | ./align-ampersands
foo                                                                            &
                                                                               &
bar                                                                            &
baz

If your input contains TAB characters, you will need to use more sophisticated processing.

Upvotes: 2

Related Questions