【问题标题】:How to preserve leading spaces whern reading from a here-document with read? [duplicate]从带有读取的此处文档中读取时如何保留前导空格? [复制]
【发布时间】:2021-02-25 17:11:56
【问题描述】:

使用以下时

read -r -d '' VAR <<EOF
  first line
  second line
EOF
echo "$VAR"

第一行的前导空格被修剪:

first line
  second line

如何回显第一行中的前导空格并获得以下内容?

  first line
  second line

请注意,这是一个简化的示例,我需要使用here document

【问题讨论】:

  • 只需在read 之前添加IFS= IFS= read ...。请注意,这也会保留最后一个换行符。
  • 从文件或 here-document 读取没有什么不同。您的问题在这里有答案:Use Bash to read line by line and keep space

标签: bash input trim


【解决方案1】:

当您将read 放入您指定为参数的变量中时,IFS 中的前导和结束字符被视为分隔符,因此被删除。

第一个解决方案:暂时清空 IFS

IFS= read -r -d '' VAR <<EOF
  first line
  second line
EOF
printf '%s\n' "$VAR"

第二种解决方案(不可移植):不指定变量,Bash 将使用默认变量REPLY

read -r -d '' <<EOF
  first line
  second line
EOF
printf '%s\n' "$REPLY"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2014-01-13
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多