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
878 views
in Technique[技术] by (71.8m points)

variables - How to remove a newline from a string in Bash

I have the following variable.

echo "|$COMMAND|"

which returns

|
REBOOT|

How can I remove that first newline?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Under , there are some bashisms:

The tr command could be replaced by // bashism:

COMMAND=$'
REBOOT
   
'
echo "|${COMMAND}|"
|
   OOT
|

echo "|${COMMAND//[$'
']}|"
|REBOOT   |

echo "|${COMMAND//[$'
 ']}|"
|REBOOT|

See Parameter Expansion and QUOTING in bash's man page:

man -Pless +//pattern bash
man -Pless +/\'string\' bash

man -Pless +/^\ *Parameter\ Exp bash
man -Pless +/^\ *QUOTING bash

Further...

As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND do contain spaces...

COMMAND=$'         
        RE BOOT      
           
'
echo "|$COMMAND|"
|
           BOOT      
|

CLEANED=${COMMAND//[$'
']}
echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
|                 RE BOOT|

CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|

Shortly:

COMMAND=$'         
        RE BOOT      
           
'
CLEANED=${COMMAND//[$'
']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|

Note: have extglob option to be enabled (shopt -s extglob) in order to use *(...) syntax.


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

...