How to remove carriage return and newline from a variable in shell script

前端 未结 6 1764
挽巷
挽巷 2020-12-01 05:57

I am new to shell script. I am sourcing a file, which is created in Windows and has carriage returns, using the source command. After I source when I append som

相关标签:
6条回答
  • 2020-12-01 06:40

    Because the file you source ends lines with carriage returns, the contents of $testVar are likely to look like this:

    $ printf '%q\n' "$testVar"
    $'value123\r'
    

    (The first line's $ is the shell prompt; the second line's $ is from the %q formatting string, indicating $'' quoting.)

    To get rid of the carriage return, you can use shell parameter expansion and ANSI-C quoting (requires Bash):

    testVar=${testVar//$'\r'}
    

    Which should result in

    $ printf '%q\n' "$testVar"
    value123
    
    0 讨论(0)
  • 2020-12-01 06:53

    for a pure shell solution without calling external program:

    NL=$'\n'    # define a variable to reference 'newline'
    
    testVar=${testVar%$NL}    # removes trailing 'NL' from string
    
    0 讨论(0)
  • 2020-12-01 06:55

    You can use sed as follows:

    MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
    echo ${MY_NEW_VAR} got it
    

    By the way, try to do a dos2unix on your data file.

    0 讨论(0)
  • 2020-12-01 07:00

    use this command on your script file after copying it to Linux/Unix

    perl -pi -e 's/\r//' scriptfilename
    
    0 讨论(0)
  • 2020-12-01 07:02

    yet another solution uses tr:

    echo $testVar | tr -d '\r'
    cat myscript | tr -d '\r'
    

    the option -d stands for delete.

    0 讨论(0)
  • 2020-12-01 07:02

    Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

    0 讨论(0)
提交回复
热议问题