Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dos2unix in a variable

Tags:

bash

dos2unix

I need to execute the dos2unix command in a variable. With files we just do dos2unix myfile.txt. How can I do that with a variable? For example:

variable="bla\r"
dos2unix $variable

Sugestions using other commands are also welcome.

PS.: I cannot perform a dos2unix on the file from where I'm reading the text.

like image 589
hbelmiro Avatar asked Oct 24 '25 04:10

hbelmiro


1 Answers

There's no need for any external command here; you can use parameter expansion to remove CRs using only functionality built into the shell itself, thus both faster to execute (with reasonably short strings) and guaranteed to work on any system that has bash (or a similarly extended shell, such as ksh93 or zsh), even without dos2unix installed:

$ PS1='> ' # for readability, to distinguish output starting with '$' literals
> variable_in=$'bla\r'
> variable_out=${variable_in//$'\r'/}
> printf '%q\n' "$variable_in"
$'bla\r'
> printf '%q\n' "$variable_out"
bla
like image 199
Charles Duffy Avatar answered Oct 26 '25 04:10

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!