Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

bash - How to add blank space in the middle of the line if the line is less than fixed length?

I would like to add blank space in the middle of the text file if the length of any line is less than the fixed length(10). The position of blank space is fixed after the 4th character.

File like this:

ABCEFGH  K<— length: 10
ABCDE  FGH<- length: 10
ABCD  EFG<- length: 9
ABCDE FGH<- length: 9
ABCDE<-length: 5

Desired output:

ABCEFGH  K<— length: 10
ABCDE  FGH<- length: 10
ABCD   EFG<- length: 10
ABCD  EFGH<- length: 10
ABCD     E<- length: 10

I’m really new to bash. I have tried approach like using awk and sed to append 0 if the line is less than fixed length. It works perfect but what I would like to achieve is to add blank space at given position and so to modify the original file.

I appreciate for any insights!

Approach that I tried: < https://stackoverflow.com/questions/46443750/appending-0s-to-a-file-in-unix-bash-if-the-line-is-less-than-a-fixed-length/46443954>

Updated:

awk '{ if(length<10) printf "%s%0*d
",$0,10-length,0; else print }' test.txt

This is the code from the above link that I have tried. As I couldn’t figure out the way to add blank space in the middle, and keep every line in the fixed length, so I couldn’t provide the code for it. I apologise for not providing the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please see this guide for asking a good question.

sed can do this.

$: cat tst
ABCEFGH  K
ABCDE  FGH
ABCD  EFG
ABCDE FGH
ABCDE
ABCD
ABC
AB
A



$: sed -E '/^.{1,9}$/{
   / [^ ]/{ s/$/          /; s/^(.{10}).*/1/; s/^([^ ]*)( +)([^ ]+)( *)/1243/;  }
   /^[^ ]+$/{ s/ //g; s/$/          /; s/^(.{10}).*/1/; s/^(.*)([^ ])( *)$/132/; }
}' tst
ABCEFGH  K
ABCDE  FGH
ABCD   EFG    
ABCDE  FGH
ABCD     E
ABC      D
AB       C
A        B
         A

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...