0

I try to create a script for a template. In this, I want to replace Strings on a static position. But after the first sed try, the default String is corrupted.

my script:

#!/bin/sh
# default record
record="NNNNNNNNNNNNNNNNNNNN CCCCCCCCCCCCCCCCCCCC BBBBBBBBBB 001"
echo "$record"

# read values from configuration file
VAR1="User Name:     Sibob" # 20
VAR2="              Berlin" # 20
VAR3="1983  [US]" # 10

record=`echo $record | sed -e "s/\(.\{0\}\)\(.\{20\}\)/\1$VAR1/" `
echo "$record"
record=`echo $record | sed -e "s/\(.\{21\}\)\(.\{20\}\)/\1$VAR2/" `
echo "$record"
record=`echo $record | sed -e "s/\(.\{54\}\)\(.\{10\}\)/\1$VAR3/" `
echo "$record"

the result of the script is:

$ ./rename.sh
NNNNNNNNNNNNNNNNNNNN CCCCCCCCCCCCCCCCCCCC BBBBBBBBBB 001
User Name:     Sibob CCCCCCCCCCCCCCCCCCCC BBBBBBBBBB 001
User Name: Sibob CCCC              BerlinBBBBBBB 001
User Name: Sibob CCCC BerlinBBBBBBB 001
User Name: Sibob CCCC BerlinBBBBBBB 001

But what I want is:

User Name:     Sibob               Berlin  1983 [US] 001

The problem is, that the blanks will be removed. In this case the replacement of the strings doesn't work correctly.

Have anyone an idea?

Tom Sibob
  • 1
  • 1

2 Answers2

0

Sounds like you should simply use printf instead.

printf '%20s %-20s %10s %03i\n' "$VAR1" "$VAR2" "$VAR3" "1"

If you insist on using sed, you can still use printf to produce the necessary padding, though perhaps refactoring your code to an Awk script would be the best route forward.

The immediate problem is that you fail to quote the argument to echo, which causes the shell to perform whitespace tokenization and wildcard expansion on the value, effectively squashing any whitespace in the value.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • For details about shell quoting, see http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable – tripleee Jul 19 '16 at 13:09
0

Thanks for the hint. Yes, printf would be better for this.

The following script works as I wanted. THANKS!

#!/bin/sh
# default record
record="NNNNNNNNNNNNNNNNNNNN;CCCCCCCCCCCCCCCCCCCC;BBBBBBBBBB;001"
echo "$record"

# read values from configuration file
VAR1="User Name:     Sibob" # 20
VAR2="              Berlin" # 20
VAR3="1983  [US]" # 10

record=`printf "%s$record" | sed -e "s/\(.\{0\}\)\(.\{20\}\)/\1$VAR1/" `
record=`printf "%s$record" | sed -e "s/\(.\{21\}\)\(.\{20\}\)/\1$VAR2/" `
record=`printf "%s$record" | sed -e "s/\(.\{42\}\)\(.\{10\}\)/\1$VAR3/" `

echo "$record" >> myFile.csv
Tom Sibob
  • 1
  • 1