Earl Tsui
Earl Tsui

Reputation: 61

Use sed to add space N times

Pattern: Mary walks at the park every day with her children

sed 's/$/ /'

will make it add 1 space at the end (trailing)

I want to add X ($VARIABLE) number of spaces (which comes from RANDOM)

i.e. VARIABLE='14' then it will do:

sed 's/$/              /'

= 14 spaces added at the end.....

Some suggestions how to do that?

I tried to do it adding unicode xA0 but it didn't work

Thanks!

Upvotes: 0

Views: 1761

Answers (7)

Tiago Lopo
Tiago Lopo

Reputation: 7959

If you can use perl try this:

perl -pe '$char=" "; $n=14; $str="$char"x$n; s/$/$str/'

In action (for better visualization I am setting $char to ".") :

perl -pe '$char="."; $n=14; $str="$char"x$n; s/$/$str/' <<< 'abc' 
abc..............

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

NSpace=15

sed "1 {x
:pre
   s/^/ /
   / \\{${NSpace}\\}/ !b pre
   x
   }
G;s/\n//" YourFile

posix sed version. More for fun than to be efficient compare to awk, perl or even bash script

Upvotes: 1

ghoti
ghoti

Reputation: 46856

My awk solution looks more like this:

awk -v num=14 '{printf("%s%"num"s\n", $0, "")}' input.txt

Of course, it might need to be adapted if you have funny line endings.

It works by using a printf format that has a second field with a fixed size, a size which is specified using the num variable inserted into the awk script by the -v option. If you use this, be sure that num is actually a number, or you're break your format.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246942

Bash: taking advantage of printf's * width specifier

$ n=15
$ printf -v spaces '%*s' $n " "
$ echo ">$spaces<"
>               <

Similarly with awk

$ spaces2=$(awk -v n=$n 'BEGIN {printf "%*s", n, " "}')
$ echo ">$spaces2<"
>               <

You can then use this string of spaces in your sed call (or decide that you don't need sed at all, that part is unclear)

Upvotes: 0

John1024
John1024

Reputation: 113864

Since this post is tagged awk, here is an awk solution:

awk -v "count=$VARIABLE" '{for (n=1;n<=count;n++)$0=$0" "} 1'

This solution takes advantage of awk's native ability to define and manipulate arithmetic variables, a capability that sed lacks.

How it works

  • -v "count=$VARIABLE"

    This sets the awk variable count to the value of the shell variable VARIABLE.

  • for (n=1;n<=count;n++)$0=$0" "

    This adds a space to the end of the line count times.

  • 1

    This is cryptic shorthand which means print the line. (The more explicit version would be {print $0}.)

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185284

If you are open to :

$ echo ok |
    perl -Mutf8 -CS -pe 's/$/sprintf "%s", (chr oct "0x2009") x (int(rand 10)) . "x"/e'

OUTPUT:

ok        x

piped with od -c :

0000000   o   k 342 200 211 342 200 211   x  \n
0000012

Upvotes: 0

SMA
SMA

Reputation: 37033

Try something like:

sed "/$/i $(printf '%.0s-' {0..14})" myfile.txt

Upvotes: 1

Related Questions