How can I have a newline in a string in sh?

后端 未结 13 777
北恋
北恋 2020-11-22 17:17

This

STR=\"Hello\\nWorld\"
echo $STR

produces as output

Hello\\nWorld

instead of

Hello
Wo         


        
相关标签:
13条回答
  • 2020-11-22 17:51

    Those picky ones that need just the newline and despise the multiline code that breaks indentation, could do:

    IFS="$(printf '\nx')"
    IFS="${IFS%x}"
    

    Bash (and likely other shells) gobble all the trailing newlines after command substitution, so you need to end the printf string with a non-newline character and delete it afterwards. This can also easily become a oneliner.

    IFS="$(printf '\nx')" IFS="${IFS%x}"
    

    I know this is two actions instead of one, but my indentation and portability OCD is at peace now :) I originally developed this to be able to split newline-only separated output and I ended up using a modification that uses \r as the terminating character. That makes the newline splitting work even for the dos output ending with \r\n.

    IFS="$(printf '\n\r')"
    
    0 讨论(0)
提交回复
热议问题