简体   繁体   中英

How to add indentation in shell script

I wrote the following script:

while read ligne;
do 
    echo ${ligne} >> /tmp/test.conf; 
    other code lines but it's not our probem.
done  < <(cat file.conf | sed -ne '/toto/,$p');

file.conf contain data like it:

test1 {
  var2 {}
}
toto {
  var1 {
    next {}
  }
}

the script must write in a file /tmp/test.conf

toto {
  var1 {
    next {}
  }
}

with the indentation.

Today I arrive to have this result:

toto {
var1 {
next {}
}
}

I try to modify my script by adding IFS variable like that:

(IFS='\n';
while read ligne;
do 
    echo ${ligne} >> /tmp/test.conf; 
    other code lines but it's not our probem.
done  < <(cat file.conf | sed -ne '/toto/,$p'));

I have the indentation but all the n letter in the result has been deleted.

toto {
  var1 {
    ext {}
  }
}

Why? How can I resolve it?

You can use this loop with IFS= before read :

while IFS= read -r ligne; do
   echo "$ligne" >> /tmp/test.conf
done < <(sed -ne '/toto/,$p' file.conf)

OR else make sure of internal variable REPLY :

while read; do
   echo "$REPLY" >> /tmp/test.conf
done < <(sed -ne '/toto/,$p' file.conf)

IFS must be set to an empty string, not to newline:

(IFS='';
while read ligne;
do 
    echo ${ligne} >> /tmp/test.conf; 
    # other code lines but it's not our probem.
done  < <(cat file.conf | sed -ne '/toto/,$p'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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