简体   繁体   English

bash,仅从行首删除一半空格

[英]bash, remove only half whitespaces from start of line

I need remove whitespaces from start of line, but only 1/2, for example: 我需要从行首删除空格,但是只有1/2,例如:

    <div class="section" id="contact">
    <div class="container">
        <div class="col-md-12">
            <h4>04</h4>

to

  <div class="section" id="contact">
  <div class="container">
    <div class="col-md-12">
      <h4>04</h4>

etc. 等等

Thanks in advance for any suggestion. 预先感谢您的任何建议。

using group in sed 在sed中使用group

sed 's/^\([[:blank:]]\{1,\}\)\1/\1/' YourFile

you can use a white space instead of [[:blank:]] if you are sure it's space and not tab. 如果确定空格而不是制表符,则可以使用空格代替[[:blank:]]

it do: replace a group of space by this group if it appear twice at the begining, so this is half the full group of space 它可以:如果一组空间在开始时出现两次,则用该组空间代替,因此这是整个空间组的一半

You can try Perl 您可以尝试Perl

perl -pe  's!(^\s+)!$x=length($1)/2;" " x $x!sme ' input_file

with your given inputs 用您给定的输入

$ cat stanislav.txt
    <div class="section" id="contact">
    <div class="container">
        <div class="col-md-12">
            <h4>04</h4>

$ perl -pe  's!(^\s+)!$x=length($1)/2;" " x $x!sme ' stanislav.txt
  <div class="section" id="contact">
  <div class="container">
    <div class="col-md-12">
      <h4>04</h4>

$

Assuming all your leading white space is blank chars: 假设所有前导空白都是空白字符:

$ awk 'match($0,/^ */){$0=sprintf("%*s%s", int(RLENGTH/2), "", substr($0,RLENGTH+1))} 1' file
  <div class="section" id="contact">
  <div class="container">
    <div class="col-md-12">
      <h4>04</h4>

If not then run your file through pr -e -t first to make it so. 如果没有,那么首先通过pr -e -t运行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM